<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/InvoiceModels.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/TenantDB.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/components/headers/page-header.php';

// Check permission - Invoice settings requires invoices_edit permission
requirePermission('invoices_edit');

$errors = [];
$successMessage = $_GET['success'] ?? null;

// Get workspace from URL parameter or session
$workspace = $_GET['workspace'] ?? $_SESSION['workspace'] ?? null;

// Resolve company ID for logging based on workspace, with TenantDB fallback
$companyIdForLog = null;
if ($workspace && !is_array($workspace)) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT id FROM companies WHERE username = ?');
        $stmt->execute([$workspace]);
        $companyRow = $stmt->fetch();
        if ($companyRow && !empty($companyRow['id'])) {
            $companyIdForLog = (int) $companyRow['id'];
        }
    } catch (Throwable $e) {
        // ignore, will fall back to TenantDB
    }
}
if (!$companyIdForLog) {
    $tenantId = TenantDB::getTenant();
    if ($tenantId) {
        $companyIdForLog = (int) $tenantId;
    }
}

// Get settings
$settings = InvoiceSettings::get() ?: [
    'company_name' => '',
    'company_legal_name' => '',
    'tax_id' => '',
    'tax_name' => '',
    'company_id' => '',
    'custom_meta' => '',
    'company_logo_path' => '',
    'address_line_1' => '',
    'address_line_2' => '',
    'city' => '',
    'state' => '',
    'zip_code' => '',
    'country' => '',
    'company_email' => '',
    'company_phone' => '',
    'bank_name' => '',
    'bank_account_name' => '',
    'bank_account_number' => '',
    'bank_routing_number' => '',
    'bank_swift' => '',
    'bank_details' => '',
    'currency' => 'USD',
    'tax_inclusive' => false,
    'payment_terms' => 'Due on Receipt',
    'authorized_signatory_name' => '',
    'authorized_signatory_designation' => '',
    'authorized_signatory_signature_path' => ''
];

// Parse custom meta
$customMeta = [];
if (!empty($settings['custom_meta'])) {
    $customMeta = json_decode($settings['custom_meta'], true) ?: [];
}

// Get tax brackets
$taxBrackets = TaxBracket::all();

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_settings') {
        // Handle custom meta fields
        $metaLabels = $_POST['meta_label'] ?? [];
        $metaValues = $_POST['meta_value'] ?? [];
        $newMeta = [];
        
        foreach ($metaLabels as $index => $label) {
            if (!empty(trim($label))) {
                $newMeta[trim($label)] = trim($metaValues[$index] ?? '');
            }
        }

        $data = [
            'company_name' => sanitizeText($_POST['company_name'] ?? ''),
            'company_legal_name' => sanitizeText($_POST['company_legal_name'] ?? ''),
            'tax_id' => sanitizeText($_POST['tax_id'] ?? ''),
            'tax_name' => sanitizeText($_POST['tax_name'] ?? ''),
            'company_registration_number' => sanitizeText($_POST['company_registration_number'] ?? ''),
            'custom_meta' => json_encode($newMeta),
            'address_line_1' => sanitizeText($_POST['address_line_1'] ?? ''),
            'address_line_2' => sanitizeText($_POST['address_line_2'] ?? ''),
            'city' => sanitizeText($_POST['city'] ?? ''),
            'state' => sanitizeText($_POST['state'] ?? ''),
            'zip_code' => sanitizeText($_POST['zip_code'] ?? ''),
            'country' => sanitizeText($_POST['country'] ?? ''),
            'company_email' => sanitizeText($_POST['company_email'] ?? ''),
            'company_phone' => sanitizeText($_POST['company_phone'] ?? ''),
            'bank_name' => sanitizeText($_POST['bank_name'] ?? ''),
            'bank_account_name' => sanitizeText($_POST['bank_account_name'] ?? ''),
            'bank_account_number' => sanitizeText($_POST['bank_account_number'] ?? ''),
            'bank_routing_number' => sanitizeText($_POST['bank_routing_number'] ?? ''),
            'bank_swift' => sanitizeText($_POST['bank_swift'] ?? ''),
            'bank_details' => sanitizeText($_POST['bank_details'] ?? ''),
            'currency' => sanitizeText($_POST['currency'] ?? 'USD'),
            'tax_inclusive' => isset($_POST['tax_inclusive']),
            'payment_terms' => sanitizeText($_POST['payment_terms'] ?? 'Due on Receipt'),
            'custom_payment_terms' => json_encode(array_filter($_POST['custom_payment_terms'] ?? [])),
            'authorized_signatory_name' => sanitizeText($_POST['authorized_signatory_name'] ?? ''),
            'authorized_signatory_designation' => sanitizeText($_POST['authorized_signatory_designation'] ?? ''),
            'authorized_signatory_signature_path' => sanitizeText($_POST['authorized_signatory_signature_path'] ?? '')
        ];

        if (InvoiceSettings::save($data)) {
            // Log invoice settings update (best-effort)
            try {
                if ($companyIdForLog) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyIdForLog,
                        $userId ? (int) $userId : null,
                        'invoice_settings_updated',
                        'invoice_settings',
                        null,
                        null,
                        null,
                        $data
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            redirect('/invoice_settings.php?workspace=' . urlencode($workspace), ['success' => 'Settings updated successfully!']);
        } else {
            $errors[] = 'Failed to update settings.';
        }
    }

    if ($action === 'upload_logo') {
        if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['company_logo'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
            
            if (!in_array($file['type'], $allowedTypes)) {
                $errors[] = 'Invalid file type. Please upload JPEG, PNG, GIF, or SVG.';
            } elseif ($file['size'] > 2 * 1024 * 1024) {
                $errors[] = 'File size too large. Maximum size is 2MB.';
            } else {
                // Get company info for workspace context
                $pdo = getPDO();
                $stmt = $pdo->prepare('SELECT * FROM companies WHERE username = ?');
                $stmt->execute([$workspace]);
                $company = $stmt->fetch();
                
                if (!$company) {
                    $errors[] = 'Company not found.';
                } else {
                    // Create company-specific upload directory
                    $uploadDir = __DIR__ . '/../storage/companies/' . $company['id'] . '/logos/';
                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0755, true);
                    }
                    
                    $fileName = 'company_logo_' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                    $uploadPath = $uploadDir . $fileName;
                    
                    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                        $logoPath = '/storage/companies/' . $company['id'] . '/logos/' . $fileName;
                        if (InvoiceSettings::updateLogo($logoPath)) {
                            // Log invoice logo upload (best-effort)
                            try {
                                if ($companyIdForLog) {
                                    $currentUser = AuthManager::getCurrentUser();
                                    $userId = $currentUser['id'] ?? null;
                                    ActivityLog::log(
                                        (int) $companyIdForLog,
                                        $userId ? (int) $userId : null,
                                        'invoice_logo_uploaded',
                                        'invoice_settings',
                                        null,
                                        null,
                                        null,
                                        ['logo_path' => $logoPath]
                                    );
                                }
                            } catch (Throwable $e) {
                                // ignore logging failures
                            }
                            redirect('/invoice_settings.php?workspace=' . urlencode($workspace), ['success' => 'Logo uploaded successfully!']);
                        } else {
                            $errors[] = 'Failed to save logo path.';
                        }
                    } else {
                        $errors[] = 'Failed to upload file.';
                    }
                }
            }
        } else {
            $errors[] = 'Please select a file to upload.';
        }
    }

    // Handle signature upload
    if ($action === 'upload_signature') {
        header('Content-Type: application/json');
        
        if (isset($_FILES['signature_upload']) && $_FILES['signature_upload']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['signature_upload'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            
            if (!in_array($file['type'], $allowedTypes)) {
                echo json_encode(['success' => false, 'message' => 'Invalid file type. Please upload JPEG, PNG, or GIF.']);
                exit;
            } elseif ($file['size'] > 2 * 1024 * 1024) {
                echo json_encode(['success' => false, 'message' => 'File size too large. Maximum size is 2MB.']);
                exit;
            } else {
                // Get company info for workspace context
                $pdo = getPDO();
                $stmt = $pdo->prepare('SELECT * FROM companies WHERE username = ?');
                $stmt->execute([$workspace]);
                $company = $stmt->fetch();
                
                if (!$company) {
                    echo json_encode(['success' => false, 'message' => 'Company not found.']);
                    exit;
                }
                
                // Create company-specific upload directory
                $uploadDir = __DIR__ . '/../storage/companies/' . $company['id'] . '/signatures/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileName = 'signature_' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                    $signaturePath = '/storage/companies/' . $company['id'] . '/signatures/' . $fileName;
                    
                    // Update the signature path in settings
                    $currentSettings = InvoiceSettings::get() ?: [];
                    $currentSettings['authorized_signatory_signature_path'] = $signaturePath;
                    
                    if (InvoiceSettings::save($currentSettings)) {
                        // Log invoice signature upload (best-effort)
                        try {
                            if ($companyIdForLog) {
                                $currentUser = AuthManager::getCurrentUser();
                                $userId = $currentUser['id'] ?? null;
                                ActivityLog::log(
                                    (int) $companyIdForLog,
                                    $userId ? (int) $userId : null,
                                    'invoice_signature_uploaded',
                                    'invoice_settings',
                                    null,
                                    null,
                                    null,
                                    ['signature_path' => $signaturePath]
                                );
                            }
                        } catch (Throwable $e) {
                            // ignore logging failures
                        }
                        echo json_encode(['success' => true, 'signature_path' => $signaturePath]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Failed to save signature path.']);
                    }
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to upload file.']);
                }
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Please select a file to upload.']);
        }
        exit;
    }

    // Handle signature removal
    if ($action === 'remove_signature') {
        header('Content-Type: application/json');
        
        $currentSettings = InvoiceSettings::get() ?: [];
        $signaturePath = $currentSettings['authorized_signatory_signature_path'] ?? '';
        
        // Delete the file if it exists
        if (!empty($signaturePath)) {
            $filePath = __DIR__ . '/..' . $signaturePath;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        
        // Update settings to remove signature path
        $currentSettings['authorized_signatory_signature_path'] = '';
        
        if (InvoiceSettings::save($currentSettings)) {
            // Log invoice signature removal (best-effort)
            try {
                if ($companyIdForLog) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyIdForLog,
                        $userId ? (int) $userId : null,
                        'invoice_signature_removed',
                        'invoice_settings',
                        null,
                        null,
                        ['signature_path' => $signaturePath],
                        null
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to remove signature.']);
        }
        exit;
    }

    if ($action === 'add_tax_bracket') {
        $data = [
            'name' => sanitizeText($_POST['tax_name'] ?? ''),
            'rate' => (float) ($_POST['tax_rate'] ?? 0),
            'description' => sanitizeText($_POST['tax_description'] ?? ''),
            'jurisdiction' => sanitizeText($_POST['tax_jurisdiction'] ?? ''),
            'is_compound' => isset($_POST['tax_is_compound']),
            'is_active' => isset($_POST['tax_is_active'])
        ];

        if (empty($data['name'])) {
            $errors[] = 'Tax name is required.';
        } elseif ($data['rate'] < 0 || $data['rate'] > 100) {
            $errors[] = 'Tax rate must be between 0 and 100.';
        } else {
            $data['rate'] = $data['rate'] / 100; // Convert percentage to decimal
            if (TaxBracket::create($data)) {
                // Log tax bracket creation (best-effort)
                try {
                    if ($companyIdForLog) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyIdForLog,
                            $userId ? (int) $userId : null,
                            'tax_bracket_created',
                            'tax_bracket',
                            null,
                            $data['name'] ?? null,
                            null,
                            $data
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }
                redirect('/invoice_settings.php?workspace=' . urlencode($workspace), ['success' => 'Tax bracket added successfully!']);
            } else {
                $errors[] = 'Failed to add tax bracket.';
            }
        }
    }

    if ($action === 'update_tax_bracket') {
        $taxId = (int) ($_POST['tax_id_hidden'] ?? 0);
        if ($taxId > 0) {
            $data = [
                'name' => sanitizeText($_POST['tax_name'] ?? ''),
                'rate' => (float) ($_POST['tax_rate'] ?? 0),
                'description' => sanitizeText($_POST['tax_description'] ?? ''),
                'jurisdiction' => sanitizeText($_POST['tax_jurisdiction'] ?? ''),
                'is_compound' => isset($_POST['tax_is_compound']),
                'is_active' => isset($_POST['tax_is_active'])
            ];

            if (empty($data['name'])) {
                $errors[] = 'Tax name is required.';
            } elseif ($data['rate'] < 0 || $data['rate'] > 100) {
                $errors[] = 'Tax rate must be between 0 and 100.';
            } else {
                $data['rate'] = $data['rate'] / 100; // Convert percentage to decimal
                if (TaxBracket::update($taxId, $data)) {
                    redirect('/invoice_settings.php?workspace=' . urlencode($workspace), ['success' => 'Tax bracket updated successfully!']);
                } else {
                    $errors[] = 'Failed to update tax bracket.';
                }
            }
        }
    }

    if ($action === 'delete_tax_bracket') {
        $taxId = (int) ($_POST['tax_id'] ?? 0);
        if ($taxId > 0) {
            if (TaxBracket::isInUse($taxId)) {
                $errors[] = 'Cannot delete tax bracket that is in use by invoice items.';
            } else {
                if (TaxBracket::delete($taxId)) {
                    redirect('/invoice_settings.php?workspace=' . urlencode($workspace), ['success' => 'Tax bracket deleted successfully!']);
                } else {
                    $errors[] = 'Failed to delete tax bracket.';
                }
            }
        }
    }
}

// Refresh data after changes
$settings = InvoiceSettings::get() ?: $settings;
$customMeta = [];
if (!empty($settings['custom_meta'])) {
    $customMeta = json_decode($settings['custom_meta'], true) ?: [];
}
$taxBrackets = TaxBracket::all();

$currencies = [
    'USD' => 'US Dollar ($)',
    'EUR' => 'Euro (€)',
    'GBP' => 'British Pound (£)',
    'CAD' => 'Canadian Dollar (C$)',
    'AUD' => 'Australian Dollar (A$)',
    'JPY' => 'Japanese Yen (¥)',
    'CHF' => 'Swiss Franc (CHF)',
    'CNY' => 'Chinese Yuan (¥)',
    'INR' => 'Indian Rupee (₹)'
];
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

$workspaceQuery = $workspace ? '?workspace=' . urlencode((string) $workspace) : '';
?>
<!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>Invoice Settings · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css?v=<?= (int) @filemtime(__DIR__ . '/assets/styles/app.build.css') ?>">
</head>
<body>
<?php renderNavigationNew('Invoices', $currentTheme); ?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'Invoice items',
            'url' => '/invoice_items.php',
            'type' => 'secondary',
            'icon' => 'M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4',
            'append_workspace' => true,
        ],
        [
            'label' => 'Templates',
            'url' => '/templates.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: 'Invoice settings',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

<main class="dash-container">
        <!-- Header -->
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                <div style="display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-start; justify-content: space-between;">
                    <div>
                        <p class="section-title">Invoices</p>
                        <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">Invoice settings</h2>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Configure company details, invoice defaults, tax brackets, and branding.</p>
                    </div>
                    <span class="status-chip">Settings</span>
                </div>
            </section>
        </div>

        <!-- Success/Error Messages -->
        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span><?= h($successMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <p style="margin: 0 0 6px; font-weight: 600;">Please fix the following errors:</p>
                    <ul class="status-list">
                        <?php foreach ($errors as $error): ?>
                            <li><?= h($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        <?php endif; ?>

        <table style="width: 100%; border-collapse: separate; border-spacing: 0; table-layout: fixed; margin-top: 24px;">
            <colgroup>
                <col style="width: auto;">
                <col style="width: 360px;">
            </colgroup>
            <tbody>
                <tr>
                    <td style="vertical-align: top; padding-right: 24px;">
        <!-- Main Settings Form - Unified -->
        <div style="display: flex; flex-direction: column; gap: 24px;">
                <form method="POST" id="mainSettingsForm">
                    <input type="hidden" name="action" value="update_settings">
                    
                    <!-- Company Information -->
                    <section class="card">
                        <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                            <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 8px;">
                                <svg style="width: 16px; height: 16px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                                </svg>
                                Company Information
                            </h2>
                        </div>
                        <div class="form-grid">
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Company Name <span style="color: var(--danger);">*</span></label>
                                    <input type="text" name="company_name" value="<?= h($settings['company_name']) ?>" required class="input" placeholder="Your Company Name">
                                </div>
                                
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Company Legal Name</label>
                                    <input type="text" name="company_legal_name" value="<?= h($settings['company_legal_name']) ?>" class="input" placeholder="Legal business name">
                                </div>
                                
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Tax Name</label>
                                    <input type="text" name="tax_name" value="<?= h($settings['tax_name']) ?>" class="input" placeholder="e.g., GSTIN, VAT">
                                </div>
                                
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Tax Number</label>
                                    <input type="text" name="tax_id" value="<?= h($settings['tax_id']) ?>" class="input" placeholder="e.g., 1946953239685566K">
                                </div>
                                
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Company ID</label>
                                    <input type="text" name="company_id" value="<?= h((string) ($settings['company_id'] ?? '')) ?>" class="input" placeholder="e.g., ABC Corp">
                                </div>
                                
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Company ID Number</label>
                                    <input type="text" name="company_registration_number" value="<?= h($settings['company_registration_number'] ?? '') ?>" class="input" placeholder="Business registration number">
                                </div>
                    </div>

                        <!-- Custom Meta Fields -->
                        <div style="margin-top: 16px;">
                            <div style="display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                                <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;">
                                    <svg style="width: 14px; height: 14px; margin-right: 8px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path>
                                    </svg>
                                    Additional Custom Meta Fields
                                </h3>
                                <button type="button" onclick="addMetaField()" class="btn-secondary btn-sm">
                                    Add Field
                                </button>
                            </div>
                            <div id="meta-fields" style="margin-top: 12px; display: flex; flex-direction: column; gap: 8px;">
                                <?php 
                                $metaIndex = 0;
                                foreach ($customMeta as $label => $value): 
                                    $metaIndex++;
                                ?>
                                    <div class="meta-field" style="display: flex; flex-wrap: wrap; gap: 8px;">
                                        <input type="text" name="meta_label[]" value="<?= h($label) ?>" placeholder="Field Label" class="input" style="flex: 1; min-width: 180px;">
                                        <input type="text" name="meta_value[]" value="<?= h($value) ?>" placeholder="Field Data" class="input" style="flex: 1; min-width: 180px;">
                                        <button type="button" onclick="removeMetaField(this)" class="btn-icon btn-icon--danger" aria-label="Remove field">
                                            <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>
                                <?php endforeach; ?>
                                <?php if ($metaIndex == 0): ?>
                                    <div class="meta-field" style="display: flex; flex-wrap: wrap; gap: 8px;">
                                        <input type="text" name="meta_label[]" placeholder="Field Label" class="input" style="flex: 1; min-width: 180px;">
                                        <input type="text" name="meta_value[]" placeholder="Field Data" class="input" style="flex: 1; min-width: 180px;">
                                        <button type="button" onclick="removeMetaField(this)" class="btn-icon btn-icon--danger" aria-label="Remove field">
                                            <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>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Company Contact Information -->
                        <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border-subtle);">
                            <p class="section-title">Contact information</p>
                            <div class="form-grid">
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Email address</label>
                                    <input type="email" name="company_email" value="<?= h($settings['company_email']) ?>" class="input" placeholder="company@example.com">
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Phone number</label>
                                    <input type="tel" name="company_phone" value="<?= h($settings['company_phone']) ?>" class="input" placeholder="+1 (555) 123-4567">
                                </div>
                            </div>
                        </div>

                        <!-- Additional Settings -->
                        <div style="margin-top: 16px;">
                            <p class="section-title">Invoice defaults</p>
                            <div class="form-grid">
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Default currency</label>
                                    <select name="currency" class="input">
                                        <?php foreach ($currencies as $code => $name): ?>
                                            <option value="<?= h($code) ?>" <?= $settings['currency'] === $code ? 'selected' : '' ?>>
                                                <?= h($name) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Default payment terms</label>
                                    <select name="payment_terms" class="input">
                                        <option value="Due on Receipt" <?= $settings['payment_terms'] === 'Due on Receipt' ? 'selected' : '' ?>>Due on Receipt</option>
                                        <option value="Net 7" <?= $settings['payment_terms'] === 'Net 7' ? 'selected' : '' ?>>Net 7</option>
                                        <option value="Net 15" <?= $settings['payment_terms'] === 'Net 15' ? 'selected' : '' ?>>Net 15</option>
                                        <option value="Net 30" <?= $settings['payment_terms'] === 'Net 30' ? 'selected' : '' ?>>Net 30</option>
                                        <option value="Net 45" <?= $settings['payment_terms'] === 'Net 45' ? 'selected' : '' ?>>Net 45</option>
                                        <option value="Net 60" <?= $settings['payment_terms'] === 'Net 60' ? 'selected' : '' ?>>Net 60</option>
                                        <option value="2% 10, Net 30" <?= $settings['payment_terms'] === '2% 10, Net 30' ? 'selected' : '' ?>>2% 10, Net 30</option>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- Custom Payment Terms -->
                            <div style="margin-top: 12px;">
                                <div style="display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 8px;">
                                    <label style="font-size: 11px; font-weight: 500; color: var(--text-tertiary);">Custom payment terms</label>
                                    <button type="button" onclick="addPaymentTerm()" class="btn-secondary btn-sm">Add term</button>
                                </div>
                                <div id="payment-terms" style="display: flex; flex-direction: column; gap: 8px;">
                                    <?php 
                                    $customTerms = [];
                                    if (!empty($settings['custom_payment_terms'])) {
                                        $customTerms = is_string($settings['custom_payment_terms']) ? json_decode($settings['custom_payment_terms'], true) : $settings['custom_payment_terms'];
                                        $customTerms = $customTerms ?? [];
                                    }
                                    if (empty($customTerms)): ?>
                                        <div class="payment-term" style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                                            <input type="text" name="custom_payment_terms[]" placeholder="e.g., Net 90, 3% 15, Net 45" class="input" style="flex: 1; min-width: 220px;">
                                            <button type="button" onclick="removePaymentTerm(this)" class="btn-icon btn-icon--danger" aria-label="Remove term">
                                                <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="M6 18L18 6M6 6l12 12"></path>
                                                </svg>
                                            </button>
                                        </div>
                                    <?php else: 
                                        foreach ($customTerms as $index => $term): ?>
                                        <div class="payment-term" style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                                            <input type="text" name="custom_payment_terms[]" value="<?= h($term) ?>" class="input" style="flex: 1; min-width: 220px;">
                                            <button type="button" onclick="removePaymentTerm(this)" class="btn-icon btn-icon--danger" aria-label="Remove term">
                                                <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="M6 18L18 6M6 6l12 12"></path>
                                                </svg>
                                            </button>
                                        </div>
                                    <?php endforeach; endif; ?>
                                </div>
                            </div>
                        </div>

                        <div style="display: flex; align-items: center; gap: 8px; margin-top: 16px;">
                            <input type="checkbox" name="tax_inclusive" id="tax_inclusive" <?= $settings['tax_inclusive'] ? 'checked' : '' ?> style="accent-color: var(--accent);">
                            <label for="tax_inclusive" style="font-size: 12px; color: var(--text-secondary);">Prices include tax by default</label>
                        </div>
                    </div>
                </div>

                <!-- Business Address -->
                <section class="card" style="margin-top: 16px;">
                    <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                        <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 8px;">
                            <svg style="width: 16px; height: 16px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                            </svg>
                            Business Address
                        </h2>
                    </div>
                    <div class="form-grid">
                        <div style="grid-column: 1 / -1;">
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Address line 1</label>
                            <input type="text" name="address_line_1" value="<?= h($settings['address_line_1']) ?>" class="input" placeholder="123 Main Street">
                        </div>
                        <div style="grid-column: 1 / -1;">
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Address line 2</label>
                            <input type="text" name="address_line_2" value="<?= h($settings['address_line_2']) ?>" class="input" placeholder="Suite 100, Building A">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">City</label>
                            <input type="text" name="city" value="<?= h($settings['city']) ?>" class="input" placeholder="New York">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">State/Province</label>
                            <input type="text" name="state" value="<?= h($settings['state']) ?>" class="input" placeholder="New York">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">ZIP code</label>
                            <input type="text" name="zip_code" value="<?= h($settings['zip_code']) ?>" class="input" placeholder="10001">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Country</label>
                            <input type="text" name="country" value="<?= h($settings['country']) ?>" class="input" placeholder="United States">
                        </div>
                    </div>
                </section>

                <!-- Business Bank Details -->
                <section class="card" style="margin-top: 16px;">
                    <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                        <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 8px;">
                            <svg style="width: 16px; height: 16px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01"></path>
                            </svg>
                            Business Bank Details
                        </h2>
                    </div>
                    <div class="form-grid">
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Bank name</label>
                            <input type="text" name="bank_name" value="<?= h($settings['bank_name']) ?>" class="input" placeholder="Bank of America">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Account name</label>
                            <input type="text" name="bank_account_name" value="<?= h($settings['bank_account_name']) ?>" class="input" placeholder="Your Company Name">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Account number</label>
                            <input type="text" name="bank_account_number" value="<?= h($settings['bank_account_number']) ?>" class="input" placeholder="123456789">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Routing number</label>
                            <input type="text" name="bank_routing_number" value="<?= h($settings['bank_routing_number']) ?>" class="input" placeholder="021000021">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">SWIFT code</label>
                            <input type="text" name="bank_swift" value="<?= h($settings['bank_swift']) ?>" class="input" placeholder="BOFAUS3N">
                        </div>
                        <div style="grid-column: 1 / -1;">
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Additional details</label>
                            <textarea name="bank_details" rows="3" class="input" style="min-height: 80px; resize: vertical;" placeholder="Additional bank information"><?= h($settings['bank_details']) ?></textarea>
                        </div>
                    </div>
                </section>

                <!-- Authorized Signatory -->
                <section class="card" style="margin-top: 16px;">
                    <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                        <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 8px;">
                            <svg style="width: 16px; height: 16px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                            </svg>
                            Authorized Signatory
                        </h2>
                    </div>
                    <div style="margin-bottom: 12px; font-size: 12px; color: var(--text-secondary);">
                        For <span style="color: var(--text-primary); font-weight: 600;"><?= h($settings['company_name'] ?: 'Your Company') ?></span>
                    </div>
                    <div class="form-grid">
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Full name</label>
                            <input type="text" name="authorized_signatory_name" value="<?= h($settings['authorized_signatory_name']) ?>" class="input" placeholder="John Doe">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Designation</label>
                            <input type="text" name="authorized_signatory_designation" value="<?= h($settings['authorized_signatory_designation']) ?>" class="input" placeholder="CEO, Director, etc.">
                        </div>
                        <div style="grid-column: 1 / -1;">
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Signature</label>
                            <?php if (!empty($settings['authorized_signatory_signature_path'])): ?>
                                <div style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
                                    <div style="padding: 8px; border: 1px solid var(--border-subtle); border-radius: 8px; background: var(--bg-surface);">
                                        <img src="<?= h($settings['authorized_signatory_signature_path']) ?>" alt="Signature" style="height: 64px; display: block;">
                                    </div>
                                    <button type="button" onclick="removeSignature()" class="btn-danger btn-sm">Remove signature</button>
                                </div>
                            <?php else: ?>
                                <div style="border: 1px dashed var(--border-default); border-radius: 10px; padding: 12px; background: var(--bg-surface); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                                    <div>
                                        <div style="font-size: 12px; font-weight: 600; color: var(--text-primary);">Upload signature</div>
                                        <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;">PNG, JPG up to 2MB</div>
                                    </div>
                                    <label for="signature_upload" class="btn-secondary btn-sm" style="cursor: pointer;">Choose file</label>
                                    <input id="signature_upload" name="signature_upload" type="file" accept="image/*" onchange="handleSignatureUpload(this)" style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;">
                                </div>
                            <?php endif; ?>
                            <input type="hidden" name="authorized_signatory_signature_path" value="<?= h($settings['authorized_signatory_signature_path']) ?>">
                        </div>
                    </div>
                </section>

                <!-- Save Button -->
                <div style="margin-top: 16px; display: flex;">
                    <button type="submit" class="btn-primary" style="width: 100%; justify-content: center; padding: 10px 14px;">
                        Save all settings
                    </button>
                </div>
            </form>
        </div>

        </div>
                    </td>
                    <td style="vertical-align: top; padding-left: 24px;">
        <!-- Sidebar -->
        <div style="display: flex; flex-direction: column; gap: 24px; width: 340px;">
            <!-- Logo Upload -->
            <section class="card">
                <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                    <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 8px;">
                        <svg style="width: 16px; height: 16px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                        </svg>
                        Company Logo
                    </h2>
                </div>
                <div>
                    <div style="display: flex; flex-direction: column; align-items: center;">
                        <?php 
                        $logoPath = $settings['company_logo_path'] ?? '';
                        $hasLogo = !empty($logoPath);
                        
                        // Simple check - if logo path exists in DB, assume it's valid
                        // The actual file existence will be checked in the modal with onerror
                        ?>
                        
                        <!-- Logo Display Area -->
                        <div style="margin-bottom: 12px;">
                            <?php if ($hasLogo): ?>
                                <div style="text-align: center;">
                                    <span class="status-chip" style="display: inline-flex; margin-bottom: 8px;">Logo uploaded</span>
                                    <div>
                                        <button type="button" onclick="viewLogo()" class="btn-secondary btn-sm">View logo</button>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div style="text-align: center;">
                                    <div style="height: 96px; width: 96px; border-radius: 10px; margin: 0 auto 12px; background: var(--bg-surface); border: 1px solid var(--border-default); display: flex; align-items: center; justify-content: center;">
                                        <svg style="width: 44px; height: 44px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                                        </svg>
                                    </div>
                                    <p style="font-size: 12px; color: var(--text-secondary); margin: 0;">No logo uploaded yet</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <form method="POST" enctype="multipart/form-data" style="width: 100%; margin-top: 12px; display: flex; flex-direction: column; gap: 10px;" id="logoUploadForm">
                            <input type="hidden" name="action" value="upload_logo">
                            
                            <div>
                                <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">
                                    <?php echo $hasLogo ? 'Replace Logo' : 'Upload Logo'; ?>
                                </label>
                                <input type="file" name="company_logo" accept="image/*" id="logo-upload" class="input" onchange="previewLogo(this)">
                                <p style="margin: 6px 0 0; font-size: 11px; color: var(--text-tertiary);">JPEG, PNG, GIF, or SVG. Maximum size: 2MB.</p>
                                
                                <!-- Logo Preview -->
                                <div id="logoPreview" class="hidden" style="margin-top: 12px;">
                                    <div style="font-size: 11px; color: var(--text-tertiary); margin-bottom: 6px;">New logo preview:</div>
                                    <div style="position: relative; display: inline-block;">
                                        <img id="previewImage" src="" alt="Logo Preview" style="height: 64px; width: 64px; object-fit: contain; border: 1px solid var(--border-subtle); border-radius: 8px; background: var(--bg-surface);">
                                        <div style="position: absolute; top: -6px; right: -6px; background: var(--success); color: #fff; border-radius: 999px; padding: 4px; display: inline-flex; align-items: center; justify-content: center;">
                                            <svg style="width: 12px; height: 12px;" fill="currentColor" viewBox="0 0 20 20">
                                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-7 7a1 1 0 01-1.414 0l-7-7A1 1 0 012 6.586V5a1 1 0 011.414-.586l7 7a1 1 0 01.586 1.414l-7 7a2 2 0 01-2.828 0l-7-7a2 2 0 012.828 0l7-7z" clip-rule="evenodd"></path>
                                            </svg>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn-primary" style="width: 100%; justify-content: center; padding: 10px 14px;">
                                <?php echo $hasLogo ? 'Replace Logo' : 'Upload Logo'; ?>
                            </button>
                        </form>
                    </div>
                </div>
            </section>

            <!-- Logo View Modal -->
            <div id="logoModal" class="delete-modal-overlay hidden" style="align-items: center; justify-content: center; padding: 16px;">
                <div class="delete-modal-content" style="max-width: 720px;">
                    <div class="delete-modal-header" style="display: flex; align-items: center; justify-content: space-between; gap: 12px;">
                        <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;">Company logo</h3>
                        <button type="button" class="btn-icon" onclick="closeLogoModal()" aria-label="Close">
                            <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="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                    <div class="delete-modal-body">
                        <div style="display: flex; justify-content: center;">
                            <img id="modalLogoImage" src="<?= h($logoPath) ?>" alt="Company Logo" style="max-height: 320px; max-width: 100%; object-fit: contain;" onerror="this.style.display='none'; document.getElementById('logoError').style.display='block';">
                            <div id="logoError" style="display: none; text-align: center; color: var(--text-tertiary);">
                                <p style="margin: 0;">Logo image not found</p>
                                <p style="margin: 6px 0 0; font-size: 11px;">The logo file may have been moved or deleted.</p>
                            </div>
                        </div>
                    </div>
                    <div class="delete-modal-footer">
                        <button type="button" class="btn-secondary" style="flex: 1;" onclick="closeLogoModal()">Close</button>
                    </div>
                </div>
            </div>

            <!-- Tax Brackets -->
            <section class="card">
                <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px;">
                    <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 8px;">
                        <svg style="width: 16px; height: 16px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                        </svg>
                        Tax Brackets
                    </h2>
                </div>
                <div>
                    <!-- Add Tax Bracket Form -->
                    <div style="margin-bottom: 14px;">
                        <p class="section-title">Add tax bracket</p>
                        <form method="POST" style="display: flex; flex-direction: column; gap: 10px;">
                            <input type="hidden" name="action" value="add_tax_bracket">
                            
                            <div>
                                <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Tax name</label>
                                <input type="text" name="tax_name" required class="input" placeholder="e.g., Sales Tax">
                            </div>
                            
                            <div>
                                <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Rate (%)</label>
                                <input type="number" name="tax_rate" step="0.01" min="0" max="100" required class="input" placeholder="8.75">
                            </div>
                            
                            <div>
                                <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Jurisdiction</label>
                                <input type="text" name="tax_jurisdiction" class="input" placeholder="e.g., State, Federal">
                            </div>
                            
                            <div style="display: flex; align-items: center; gap: 14px; flex-wrap: wrap;">
                                <label style="display: inline-flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-secondary);">
                                    <input type="checkbox" name="tax_is_active" checked style="accent-color: var(--accent);">
                                    Active
                                </label>
                                <label style="display: inline-flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-secondary);">
                                    <input type="checkbox" name="tax_is_compound" style="accent-color: var(--accent);">
                                    Compound
                                </label>
                            </div>
                            
                            <button type="submit" class="btn-primary" style="width: 100%; justify-content: center; padding: 10px 14px;">Add tax bracket</button>
                        </form>
                    </div>

                    <!-- Tax Brackets List -->
                    <div style="display: flex; flex-direction: column; gap: 8px;">
                        <?php if ($taxBrackets): ?>
                            <?php foreach ($taxBrackets as $tax): ?>
                                <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 12px 12px; border: 1px solid var(--border-default); border-radius: 10px; background: var(--bg-surface);">
                                    <div style="flex: 1; min-width: 0;">
                                        <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 6px;">
                                            <span style="font-size: 12px; font-weight: 500; color: var(--text-primary);">
                                                <?= h($tax['name']) ?>
                                            </span>
                                            <?php if (!$tax['is_active']): ?>
                                                <span class="status-chip">Inactive</span>
                                            <?php endif; ?>
                                            <?php if (($tax['is_compound'] ?? 0)): ?>
                                                <span class="status-chip">Compound</span>
                                            <?php endif; ?>
                                        </div>
                                        <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">
                                            <?= number_format($tax['rate'] * 100, 2) ?>% 
                                            <?php if ($tax['jurisdiction'] ?? ''): ?>· <?= h($tax['jurisdiction']) ?><?php endif; ?>
                                        </div>
                                    </div>
                                    <div style="display: flex; align-items: center; gap: 6px; flex-shrink: 0;">
                                        <button type="button" onclick="editTaxBracket(<?= $tax['id'] ?>)" class="btn-secondary btn-sm">Edit</button>
                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this tax bracket?')" style="display: inline;">
                                            <input type="hidden" name="action" value="delete_tax_bracket">
                                            <input type="hidden" name="tax_id" value="<?= $tax['id'] ?>">
                                            <button type="submit" class="btn-icon btn-icon--danger" aria-label="Delete tax bracket">
                                                <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>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div style="text-align: center; padding: 20px 12px; color: var(--text-tertiary);">
                                <svg style="width: 28px; height: 28px; margin-bottom: 8px;" 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>
                                <div style="font-size: 12px; color: var(--text-secondary);">No tax brackets configured</div>
                                <div style="font-size: 11px; margin-top: 4px;">Add your first tax bracket to get started</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </section>
        </div>
                    </td>
                </tr>
            </tbody>
        </table>

    <!-- Edit Tax Bracket Modal -->
    <div id="editTaxModal" class="delete-modal-overlay hidden" style="align-items: center; justify-content: center; padding: 16px;">
        <div class="delete-modal-content" style="max-width: 520px;">
            <div class="delete-modal-header" style="display: flex; align-items: center; justify-content: space-between; gap: 12px;">
                <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;">Edit tax bracket</h3>
                <button type="button" class="btn-icon" onclick="closeEditTaxModal()" aria-label="Close">
                    <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="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            <form id="editTaxForm" method="POST">
                <input type="hidden" name="action" value="update_tax_bracket">
                <input type="hidden" name="tax_id_hidden" id="editTaxId">
                <div class="delete-modal-body" style="display: flex; flex-direction: column; gap: 10px;">
                    <div>
                        <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Tax name</label>
                        <input type="text" name="tax_name" id="editTaxName" required class="input">
                    </div>
                    <div>
                        <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Rate (%)</label>
                        <input type="number" name="tax_rate" id="editTaxRate" step="0.01" min="0" max="100" required class="input">
                    </div>
                    <div>
                        <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Jurisdiction</label>
                        <input type="text" name="tax_jurisdiction" id="editTaxJurisdiction" class="input">
                    </div>
                    <div>
                        <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Description</label>
                        <textarea name="tax_description" id="editTaxDescription" rows="3" class="input"></textarea>
                    </div>
                    <div style="display: flex; align-items: center; gap: 14px; flex-wrap: wrap;">
                        <label style="display: inline-flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-secondary);">
                            <input type="checkbox" name="tax_is_active" id="editTaxActive" style="accent-color: var(--accent);">
                            Active
                        </label>
                        <label style="display: inline-flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-secondary);">
                            <input type="checkbox" name="tax_is_compound" id="editTaxCompound" style="accent-color: var(--accent);">
                            Compound
                        </label>
                    </div>
                </div>
                <div class="delete-modal-footer">
                    <button type="button" class="btn-secondary" style="flex: 1;" onclick="closeEditTaxModal()">Cancel</button>
                    <button type="submit" class="btn-primary" style="flex: 1; justify-content: center;">Save</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function addMetaField() {
            const container = document.getElementById('meta-fields');
            const newField = document.createElement('div');
            newField.className = 'meta-field';
            newField.style.display = 'flex';
            newField.style.flexWrap = 'wrap';
            newField.style.gap = '8px';
            newField.innerHTML = `
                <input type="text" name="meta_label[]" placeholder="Field Label" class="input" style="flex: 1; min-width: 180px;">
                <input type="text" name="meta_value[]" placeholder="Field Data" class="input" style="flex: 1; min-width: 180px;">
                <button type="button" onclick="removeMetaField(this)" class="btn-icon btn-icon--danger" aria-label="Remove field">
                    <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>
            `;
            container.appendChild(newField);
        }

        function removeMetaField(button) {
            const container = document.getElementById('meta-fields');
            if (container.children.length > 1) {
                button.parentElement.remove();
            }
        }

        function editTaxBracket(taxId) {
            // Find the tax bracket data from the list
            const taxBrackets = <?= json_encode($taxBrackets) ?>;
            const tax = taxBrackets.find(t => t.id == taxId);
            
            if (tax) {
                document.getElementById('editTaxId').value = tax.id;
                document.getElementById('editTaxName').value = tax.name;
                document.getElementById('editTaxRate').value = tax.rate * 100;
                document.getElementById('editTaxJurisdiction').value = tax.jurisdiction || '';
                document.getElementById('editTaxDescription').value = tax.description || '';
                document.getElementById('editTaxActive').checked = tax.is_active;
                document.getElementById('editTaxCompound').checked = tax.is_compound;

                const modal = document.getElementById('editTaxModal');
                modal.style.display = 'flex';
            }
        }

        function closeEditTaxModal() {
            const modal = document.getElementById('editTaxModal');
            modal.style.display = 'none';
        }

        function addPaymentTerm() {
            const container = document.getElementById('payment-terms');
            const newTerm = document.createElement('div');
            newTerm.className = 'payment-term';
            newTerm.style.display = 'flex';
            newTerm.style.flexWrap = 'wrap';
            newTerm.style.gap = '8px';
            newTerm.style.alignItems = 'center';
            newTerm.innerHTML = `
                <input type="text" name="custom_payment_terms[]" placeholder="e.g., Net 90, 3% 15, Net 45" class="input" style="flex: 1; min-width: 220px;">
                <button type="button" onclick="removePaymentTerm(this)" class="btn-icon btn-icon--danger" aria-label="Remove term">
                    <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="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            `;
            container.appendChild(newTerm);
        }

        function removePaymentTerm(button) {
            const container = document.getElementById('payment-terms');
            if (container.children.length > 1) {
                button.parentElement.remove();
            } else {
                // Clear the value if it's the last one
                button.parentElement.querySelector('input').value = '';
            }
        }

        function previewLogo(input) {
            const preview = document.getElementById('logoPreview');
            const previewImage = document.getElementById('previewImage');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    previewImage.src = e.target.result;
                    preview.classList.remove('hidden');
                }
                
                reader.readAsDataURL(input.files[0]);
            } else {
                preview.classList.add('hidden');
            }
        }

        function viewLogo() {
            const modal = document.getElementById('logoModal');
            const modalImage = document.getElementById('modalLogoImage');
            const logoPath = '<?= h($logoPath) ?>';
            
            // Update modal image source
            modalImage.src = logoPath;
            modal.style.display = 'flex';
        }

        function closeLogoModal() {
            const modal = document.getElementById('logoModal');
            modal.style.display = 'none';
        }

        // Handle logo upload form submission with AJAX
        document.getElementById('logoUploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;
            
            // Show loading state
            submitButton.textContent = 'Uploading...';
            submitButton.disabled = true;
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(html => {
                // Parse the response to get the new logo path
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const newLogoPath = doc.querySelector('#modalLogoImage')?.src;
                
                if (newLogoPath) {
                    // Update the modal image source
                    document.getElementById('modalLogoImage').src = newLogoPath;
                    
                    // Show success message
                    showSuccessMessage('Logo uploaded successfully!');
                    
                    // Clear the file input and preview
                    document.getElementById('logo-upload').value = '';
                    document.getElementById('logoPreview').classList.add('hidden');
                    
                    // Reload page after a short delay to show updated UI
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showErrorMessage('Upload failed. Please try again.');
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                showErrorMessage('Upload failed. Please try again.');
            })
            .finally(() => {
                // Reset button
                submitButton.innerHTML = originalText;
                submitButton.disabled = false;
            });
        });

        function showSuccessMessage(message) {
            // Remove any existing messages
            const existingMessage = document.querySelector('[data-ajax-status-message]');
            if (existingMessage) {
                existingMessage.remove();
            }
            
            // Create success message
            const messageDiv = document.createElement('div');
            messageDiv.setAttribute('data-ajax-status-message', '1');
            messageDiv.className = 'dash-section';
            messageDiv.innerHTML = `
                <div class="status-banner success"><span>${message}</span></div>
            `;
            
            // Insert at the top of main content
            const mainContent = document.querySelector('.dash-container') || document.body;
            mainContent.insertBefore(messageDiv, mainContent.firstChild);
            
            // Auto-remove after 3 seconds
            setTimeout(() => {
                messageDiv.remove();
            }, 3000);
        }
        
        function showErrorMessage(message) {
            // Remove any existing messages
            const existingMessage = document.querySelector('[data-ajax-status-message]');
            if (existingMessage) {
                existingMessage.remove();
            }
            
            // Create error message
            const messageDiv = document.createElement('div');
            messageDiv.setAttribute('data-ajax-status-message', '1');
            messageDiv.className = 'dash-section';
            messageDiv.innerHTML = `
                <div class="status-banner error"><span>${message}</span></div>
            `;
            
            // Insert at the top of main content
            const mainContent = document.querySelector('.dash-container') || document.body;
            mainContent.insertBefore(messageDiv, mainContent.firstChild);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                messageDiv.remove();
            }, 5000);
        }

        // Close modal when clicking outside
        document.getElementById('logoModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeLogoModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeLogoModal();
            }
        });

        // Close modal when clicking outside
        document.getElementById('editTaxModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditTaxModal();
            }
        });

        // Handle AJAX request for tax bracket data if needed
        <?php if (isset($_GET['get_tax'])): ?>
            $taxId = (int) ($_GET['get_tax'] ?? 0);
            if ($taxId > 0) {
                $tax = null;
                foreach ($taxBrackets as $t) {
                    if ($t['id'] == $taxId) {
                        $tax = $t;
                        break;
                    }
                }
                if ($tax) {
                    header('Content-Type: application/json');
                    echo json_encode($tax);
                    exit;
                }
            }
        <?php endif; ?>
        
        // Signature upload functions
        function handleSignatureUpload(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                
                // Validate file size (2MB max)
                if (file.size > 2 * 1024 * 1024) {
                    showErrorMessage('Signature file must be less than 2MB');
                    input.value = '';
                    return;
                }
                
                // Validate file type
                if (!file.type.match('image.*')) {
                    showErrorMessage('Signature must be an image file (PNG, JPG, etc.)');
                    input.value = '';
                    return;
                }
                
                // Create FormData for upload
                const formData = new FormData();
                formData.append('signature_upload', file);
                formData.append('action', 'upload_signature');
                
                // Upload signature
                fetch('invoice_settings.php?workspace=<?= urlencode($workspace ?? '') ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update the hidden field
                        document.querySelector('input[name="authorized_signatory_signature_path"]').value = data.signature_path;
                        
                        // Refresh the page to show the new signature
                        window.location.reload();
                    } else {
                        showErrorMessage(data.message || 'Failed to upload signature');
                        input.value = '';
                    }
                })
                .catch(error => {
                    console.error('Error uploading signature:', error);
                    showErrorMessage('Failed to upload signature');
                    input.value = '';
                });
            }
        }
        
        function removeSignature() {
            if (confirm('Are you sure you want to remove the signature?')) {
                // Create FormData for removal
                const formData = new FormData();
                formData.append('action', 'remove_signature');
                
                // Remove signature
                fetch('invoice_settings.php?workspace=<?= urlencode($workspace ?? '') ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update the hidden field
                        document.querySelector('input[name="authorized_signatory_signature_path"]').value = '';
                        
                        // Refresh the page to show the upload area
                        window.location.reload();
                    } else {
                        showErrorMessage(data.message || 'Failed to remove signature');
                    }
                })
                .catch(error => {
                    console.error('Error removing signature:', error);
                    showErrorMessage('Failed to remove signature');
                });
            }
        }
    </script>
</main>

</div>
</body>
</html>
