<?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';

// 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';
?>
<!DOCTYPE html>
<html lang="en">
<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">
</head>
<body class="bg-neutral-950 text-neutral-50 min-h-screen">
<div class="min-h-screen flex flex-col">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Invoices', $currentTheme); ?>

<div class="hidden md:block"></div>

<main class="flex-1 flex flex-col md:ml-56">
    <!-- Top Header -->
    <header class="sticky top-0 z-30 flex h-12 items-center justify-between px-3 md:px-6 border-b border-neutral-800 bg-neutral-950">
        <div class="flex items-center gap-3 flex-1 min-w-0">
            <!-- Mobile Menu Button -->
            <button id="mobile-menu-btn" class="md:hidden inline-flex items-center justify-center p-2 rounded-lg text-neutral-400 hover:text-neutral-100 hover:bg-neutral-800 transition-colors duration-200">
                <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                </svg>
            </button>

            <div class="flex items-center gap-3 min-w-0 flex-1">
                <div class="flex h-6 w-6 items-center justify-center rounded bg-neutral-800 text-neutral-100 flex-shrink-0">
                    <svg class="h-4 w-4" 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>
                </div>
                <div class="min-w-0 flex-1">
                    <h1 class="text-sm font-semibold text-neutral-50 truncate">Invoice settings</h1>
                    <p class="text-xs text-neutral-400 hidden sm:block truncate">Configure company info, tax brackets and billing details</p>
                </div>
            </div>
        </div>
    </header>

    <div class="flex-1">
    <div class="max-w-7xl mx-auto px-3 md:px-6 pt-6 pb-4">
    <!-- Header -->
    <div class="mb-4 flex items-center justify-between">
        <div>
            <h2 class="text-lg font-semibold text-neutral-50">Invoice settings</h2>
            <p class="mt-1 text-xs text-neutral-400">Configure your company information, taxes and invoice defaults</p>
        </div>
        <div class="flex items-center space-x-2">
            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-neutral-900 border border-neutral-800 text-neutral-300">
                <svg class="w-3.5 h-3.5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                </svg>
                Settings
            </span>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if ($successMessage): ?>
        <div class="mb-4 bg-emerald-500/10 border border-emerald-500/30 text-emerald-200 px-3 py-2 rounded-lg text-sm flex items-center gap-2">
            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
            </svg>
            <span><?= h($successMessage) ?></span>
        </div>
    <?php endif; ?>

    <?php if ($errors): ?>
        <div class="mb-4 bg-red-500/10 border border-red-500/20 text-red-200 px-3 py-2 rounded-lg text-sm">
            <div class="flex items-center mb-1">
                <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                </svg>
                <span class="font-medium">Please fix the following errors:</span>
            </div>
            <ul class="list-disc list-inside space-y-1 ml-5">
                <?php foreach ($errors as $error): ?>
                    <li class="text-xs leading-relaxed"><?= h($error) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Settings Form - Unified -->
        <div class="lg:col-span-2 space-y-6">
            <form method="POST" id="mainSettingsForm">
                <input type="hidden" name="action" value="update_settings">
                
                <!-- Company Information -->
                <div class="bg-neutral-900/50 rounded-xl border border-neutral-800 shadow-sm">
                    <div class="px-6 py-4 border-b border-neutral-800">
                        <h2 class="text-lg font-semibold text-neutral-50 flex items-center">
                            <svg class="w-5 h-5 mr-2 text-neutral-300" 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="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">
                                    Company Name <span class="text-rose-500">*</span>
                                </label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    </div>
                                    <input type="text" name="company_name" value="<?= h($settings['company_name']) ?>" required
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="Your Company Name">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Company Legal Name</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    <input type="text" name="company_legal_name" value="<?= h($settings['company_legal_name']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="Legal business name">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Tax Name</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="tax_name" value="<?= h($settings['tax_name']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="e.g., GSTIN, VAT">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Tax Number</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="tax_id" value="<?= h($settings['tax_id']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="e.g., 1946953239685566K">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Company ID</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V8a2 2 0 00-2-2h-5m-4 0V5a2 2 0 114 0v1m-4 0a2 2 0 104 0v1m-5 8a2 2 0 100-4 2 2 0 000 4zm0 0c1.306 0 2.417.835 2.83 2M9 14a3.001 3.001 0 00-2.83 2M15 11h3m-3 4h2"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="company_id" value="<?= h((string)$settings['company_id']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="e.g., ABC Corp">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Company ID Number</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V8a2 2 0 00-2-2h-5m-4 0V5a2 2 0 114 0v1m-4 0a2 2 0 104 0v1m-5 8a2 2 0 100-4 2 2 0 000 4zm0 0c1.306 0 2.417.835 2.83 2M9 14a3.001 3.001 0 00-2.83 2M15 11h3m-3 4h2"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="company_registration_number" value="<?= h($settings['company_registration_number'] ?? '') ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="Business registration number">
                                </div>
                            </div>
                        </div>

                        <!-- Custom Meta Fields -->
                        <div class="space-y-4 mt-6">
                            <div class="flex items-center justify-between">
                                <h3 class="text-sm font-medium text-neutral-50 flex items-center">
                                    <svg class="w-4 h-4 mr-2 text-neutral-300" 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="inline-flex items-center px-3 py-1.5 text-xs font-medium text-white bg-neutral-50 text-neutral-900 rounded-lg hover:bg-neutral-200 transition-colors">
                                    <svg class="w-3 h-3 mr-1" 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 Field
                                </button>
                            </div>
                            <div id="meta-fields" class="space-y-3">
                                <?php 
                                $metaIndex = 0;
                                foreach ($customMeta as $label => $value): 
                                    $metaIndex++;
                                ?>
                                    <div class="flex gap-3 meta-field">
                                        <div class="relative flex-1">
                                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <svg class="h-4 w-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                                                </svg>
                                            </div>
                                            <input type="text" name="meta_label[]" value="<?= h($label) ?>" placeholder="Field Label"
                                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                                        </div>
                                        <div class="relative flex-1">
                                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <svg class="h-4 w-4 text-neutral-400" 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>
                                            <input type="text" name="meta_value[]" value="<?= h($value) ?>" placeholder="Field Data"
                                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                                        </div>
                                        <button type="button" onclick="removeMetaField(this)" class="p-2 text-rose-600 hover:bg-rose-50 rounded-lg 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>
                                <?php endforeach; ?>
                                <?php if ($metaIndex == 0): ?>
                                    <div class="flex gap-3 meta-field">
                                        <div class="relative flex-1">
                                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <svg class="h-4 w-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                                                </svg>
                                            </div>
                                            <input type="text" name="meta_label[]" placeholder="Field Label"
                                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                                        </div>
                                        <div class="relative flex-1">
                                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <svg class="h-4 w-4 text-neutral-400" 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>
                                            <input type="text" name="meta_value[]" placeholder="Field Data"
                                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                                        </div>
                                        <button type="button" onclick="removeMetaField(this)" class="p-2 text-rose-600 hover:bg-rose-50 rounded-lg 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>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Company Contact Information -->
                        <div class="mt-6 pt-6 border-t border-neutral-800">
                            <h3 class="text-sm font-semibold text-neutral-50 mb-4">Contact Information</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-neutral-300 mb-2">Email Address</label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                            </svg>
                                        </div>
                                        <input type="email" name="company_email" value="<?= h($settings['company_email']) ?>"
                                               class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                               placeholder="company@example.com">
                                    </div>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-neutral-300 mb-2">Phone Number</label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>
                                            </svg>
                                        </div>
                                        <input type="tel" name="company_phone" value="<?= h($settings['company_phone']) ?>"
                                               class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                               placeholder="+1 (555) 123-4567">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Settings -->
                        <div class="mt-6">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-neutral-300 mb-2">Default Currency</label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                            </svg>
                                        </div>
                                        <select name="currency" class="w-full pl-10 pr-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">
                                            <?php foreach ($currencies as $code => $name): ?>
                                                <option value="<?= h($code) ?>" <?= $settings['currency'] === $code ? 'selected' : '' ?>>
                                                    <?= h($name) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-neutral-300 mb-2">Default Payment Terms</label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                            </svg>
                                        </div>
                                        <select name="payment_terms" class="w-full pl-10 pr-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">
                                            <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>
                            </div>
                            
                            <!-- Custom Payment Terms -->
                            <div class="mt-4">
                                <div class="flex items-center justify-between mb-3">
                                    <label class="text-sm font-medium text-slate-700">Custom Payment Terms</label>
                                    <button type="button" onclick="addPaymentTerm()" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-white bg-slate-900 rounded-lg hover:bg-slate-800 transition-colors">
                                        <svg class="w-3 h-3 mr-1" 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 Term
                                    </button>
                                </div>
                                <div id="payment-terms" class="space-y-2">
                                    <?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="flex gap-2 payment-term">
                                            <input type="text" name="custom_payment_terms[]" placeholder="e.g., Net 90, 3% 15, Net 45"
                                                   class="flex-1 px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 focus:border-slate-500 text-sm placeholder-slate-400">
                                            <button type="button" onclick="removePaymentTerm(this)" class="p-2 text-rose-600 hover:bg-rose-50 rounded-lg 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="M6 18L18 6M6 6l12 12"></path>
                                                </svg>
                                            </button>
                                        </div>
                                    <?php else: 
                                        foreach ($customTerms as $index => $term): ?>
                                        <div class="flex gap-2 payment-term">
                                            <input type="text" name="custom_payment_terms[]" value="<?= h($term) ?>"
                                                   class="flex-1 px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 focus:border-slate-500 text-sm placeholder-slate-400">
                                            <button type="button" onclick="removePaymentTerm(this)" class="p-2 text-rose-600 hover:bg-rose-50 rounded-lg 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="M6 18L18 6M6 6l12 12"></path>
                                                </svg>
                                            </button>
                                        </div>
                                    <?php endforeach; endif; ?>
                                </div>
                            </div>
                        </div>

                        <div class="flex items-center mt-6">
                            <input type="checkbox" name="tax_inclusive" id="tax_inclusive" <?= $settings['tax_inclusive'] ? 'checked' : '' ?>
                                   class="rounded border-neutral-800 text-neutral-300 focus:ring-neutral-700">
                            <label for="tax_inclusive" class="ml-2 text-sm text-neutral-300">Prices include tax by default</label>
                        </div>
                    </div>
                </div>

                <!-- Business Address -->
                <div class="bg-neutral-900/50 rounded-xl border border-neutral-800 shadow-sm mt-6">
                    <div class="px-6 py-4 border-b border-neutral-800">
                        <h2 class="text-lg font-semibold text-neutral-50 flex items-center">
                            <svg class="w-5 h-5 mr-2 text-neutral-300" 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="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Address Line 1</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                        </svg>
                                    </div>
                                    <input type="text" name="address_line_1" value="<?= h($settings['address_line_1']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="123 Main Street">
                                </div>
                            </div>
                            
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Address Line 2</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    </div>
                                    <input type="text" name="address_line_2" value="<?= h($settings['address_line_2']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="Suite 100, Building A">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">City</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    </div>
                                    <input type="text" name="city" value="<?= h($settings['city']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="New York">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">State/Province</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="state" value="<?= h($settings['state']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="New York">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">ZIP Code</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="zip_code" value="<?= h($settings['zip_code']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="10001">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Country</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="country" value="<?= h($settings['country']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="United States">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Business Bank Details -->
                <div class="bg-neutral-900/50 rounded-xl border border-neutral-800 shadow-sm mt-6">
                    <div class="px-6 py-4 border-b border-neutral-800">
                        <h2 class="text-lg font-semibold text-neutral-50 flex items-center">
                            <svg class="w-5 h-5 mr-2 text-neutral-300" 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="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Bank Name</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    </div>
                                    <input type="text" name="bank_name" value="<?= h($settings['bank_name']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="Bank of America">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Account Name</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    </div>
                                    <input type="text" name="bank_account_name" value="<?= h($settings['bank_account_name']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="Your Company Name">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Account Number</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="bank_account_number" value="<?= h($settings['bank_account_number']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="123456789">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Routing Number</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="bank_routing_number" value="<?= h($settings['bank_routing_number']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="021000021">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">SWIFT Code</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="bank_swift" value="<?= h($settings['bank_swift']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="BOFAUS3N">
                                </div>
                            </div>
                            
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Additional Details</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-start pt-2 pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    <textarea name="bank_details" rows="3"
                                              class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50 resize-none"
                                              placeholder="Additional bank information"><?= h($settings['bank_details']) ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Authorized Signatory -->
                <div class="bg-neutral-900/50 rounded-xl border border-neutral-800 shadow-sm mt-6">
                    <div class="px-6 py-4 border-b border-neutral-800">
                        <h2 class="text-lg font-semibold text-neutral-50 flex items-center">
                            <svg class="w-5 h-5 mr-2 text-neutral-300" 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 class="p-6">
                        <div class="mb-4">
                            <p class="text-sm text-neutral-300 mb-4">
                                For <strong><?= h($settings['company_name'] ?: 'Your Company') ?></strong>
                            </p>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Full Name</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" 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>
                                    </div>
                                    <input type="text" name="authorized_signatory_name" value="<?= h($settings['authorized_signatory_name']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="John Doe">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Designation</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="authorized_signatory_designation" value="<?= h($settings['authorized_signatory_designation']) ?>"
                                           class="w-full pl-10 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="CEO, Director, etc.">
                                </div>
                            </div>
                            
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-neutral-300 mb-2">Signature</label>
                                <div class="flex items-center space-x-4">
                                    <?php if (!empty($settings['authorized_signatory_signature_path'])): ?>
                                        <div class="flex-shrink-0">
                                            <img src="<?= h($settings['authorized_signatory_signature_path']) ?>" alt="Signature" class="h-16 border border-neutral-800 rounded">
                                        </div>
                                        <div class="flex-1">
                                            <p class="text-sm text-neutral-300 mb-2">Current signature:</p>
                                            <button type="button" onclick="removeSignature()" class="text-sm text-red-600 hover:text-red-700 font-medium">
                                                Remove Signature
                                            </button>
                                        </div>
                                    <?php else: ?>
                                        <div class="flex-1">
                                            <div class="border-2 border-dashed border-neutral-700 rounded-lg p-4 text-center">
                                                <svg class="mx-auto h-12 w-12 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
                                                </svg>
                                                <div class="mt-2">
                                                    <label for="signature_upload" class="cursor-pointer">
                                                        <span class="mt-2 block text-sm font-medium text-neutral-50">Upload Signature</span>
                                                        <span class="mt-1 block text-xs text-neutral-400">PNG, JPG up to 2MB</span>
                                                    </label>
                                                    <input id="signature_upload" name="signature_upload" type="file" class="sr-only" accept="image/*" onchange="handleSignatureUpload(this)">
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <input type="hidden" name="authorized_signatory_signature_path" value="<?= h($settings['authorized_signatory_signature_path']) ?>">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Save Button -->
                <div class="flex items-center space-x-3 pt-6">
                    <button type="submit" class="flex-1 inline-flex items-center justify-center px-6 py-3 bg-slate-900 text-white rounded-lg hover:bg-slate-800 transition-colors duration-200 font-medium shadow-sm hover:shadow-md">
                        <svg class="w-5 h-5 mr-2" 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>
                        Save All Settings
                    </button>
                </div>
            </form>
        </div>

        <!-- Sidebar -->
        <div class="space-y-6">
            <!-- Logo Upload -->
            <div class="bg-neutral-900/50 rounded-xl border border-neutral-800 shadow-sm">
                <div class="px-6 py-4 border-b border-neutral-800">
                    <h2 class="text-lg font-semibold text-neutral-50 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-neutral-300" 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 class="p-6">
                    <div class="flex flex-col 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 class="mb-4">
                            <?php if ($hasLogo): ?>
                                <div class="text-center">
                                    <div class="inline-flex items-center px-3 py-1.5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-200 rounded-full text-sm font-medium mb-2">
                                        <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                                        </svg>
                                        Logo Uploaded
                                    </div>
                                    <button type="button" onclick="viewLogo()" class="inline-flex items-center px-3 py-1.5 bg-neutral-50 text-neutral-900 rounded-lg hover:bg-neutral-200 transition-colors text-sm">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                        </svg>
                                        View Logo
                                    </button>
                                </div>
                            <?php else: ?>
                                <div class="text-center">
                                    <div class="h-24 w-24 bg-neutral-900 border border-neutral-800 rounded-lg mb-4 flex items-center justify-center mx-auto">
                                        <svg class="w-12 h-12 text-neutral-400" 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>
                                    </div>
                                    <p class="text-sm text-neutral-300 mb-2">No logo uploaded yet</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <form method="POST" enctype="multipart/form-data" class="w-full space-y-4" id="logoUploadForm">
                            <input type="hidden" name="action" value="upload_logo">
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-2">
                                    <?php echo $hasLogo ? 'Replace Logo' : 'Upload Logo'; ?>
                                </label>
                                <div class="relative">
                                    <input type="file" name="company_logo" accept="image/*" id="logo-upload"
                                           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 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-neutral-50 file:text-neutral-700 hover:file:bg-neutral-100 bg-neutral-950 text-neutral-50"
                                           onchange="previewLogo(this)">
                                </div>
                                <p class="mt-1 text-xs text-neutral-400">JPEG, PNG, GIF, or SVG. Maximum size: 2MB.</p>
                                
                                <!-- Logo Preview -->
                                <div id="logoPreview" class="mt-3 hidden">
                                    <div class="text-xs text-neutral-300 mb-2">New logo preview:</div>
                                    <div class="relative inline-block">
                                        <img id="previewImage" src="" alt="Logo Preview" class="h-16 w-16 object-contain border border-neutral-800 rounded">
                                        <div class="absolute -top-1 -right-1 bg-emerald-500 text-white rounded-full p-1">
                                            <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                                            </svg>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-neutral-50 text-neutral-900 rounded-lg hover:bg-neutral-200 transition-colors duration-200 font-medium text-sm shadow-sm hover:shadow-md">
                                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
                                </svg>
                                <?php echo $hasLogo ? 'Replace Logo' : 'Upload Logo'; ?>
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Logo View Modal -->
            <div id="logoModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center">
                <div class="bg-neutral-900 rounded-xl shadow-xl max-w-2xl w-full mx-4 border border-neutral-800">
                    <div class="px-6 py-4 border-b border-neutral-800 flex items-center justify-between">
                        <h3 class="text-lg font-semibold text-neutral-50">Company Logo</h3>
                        <button type="button" onclick="closeLogoModal()" class="p-2 text-neutral-400 hover:bg-neutral-800 rounded-lg transition-colors">
                            <svg class="w-5 h-5" 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="p-6">
                        <div class="flex justify-center">
                            <img id="modalLogoImage" src="<?= h($logoPath) ?>" alt="Company Logo" class="max-h-64 max-w-full object-contain" onerror="this.style.display='none'; document.getElementById('logoError').style.display='block';">
                            <div id="logoError" style="display: none;" class="text-center text-neutral-400">
                                <svg class="w-16 h-16 mx-auto mb-4 text-neutral-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 15.5c-.77.833.192 2.5 1.732 2.5z"></path>
                                </svg>
                                <p>Logo image not found</p>
                                <p class="text-sm mt-2">The logo file may have been moved or deleted</p>
                                <p class="text-xs mt-1 text-neutral-500">Debug: Path = <?= h($logoPath) ?></p>
                            </div>
                        </div>
                        <div class="mt-4 text-center text-sm text-neutral-300">
                            Current company logo
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tax Brackets -->
            <div class="bg-neutral-900/50 rounded-xl border border-neutral-800 shadow-sm">
                <div class="px-6 py-4 border-b border-neutral-800">
                    <h2 class="text-lg font-semibold text-neutral-50 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-neutral-300" 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 class="p-6">
                    <!-- Add Tax Bracket Form -->
                    <div class="mb-6">
                        <h3 class="text-sm font-medium text-neutral-50 mb-4 flex items-center">
                            <svg class="w-4 h-4 mr-2 text-neutral-300" 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 New Tax Bracket
                        </h3>
                        <form method="POST" class="space-y-3">
                            <input type="hidden" name="action" value="add_tax_bracket">
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-1">Tax Name</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-4 w-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="tax_name" required
                                           class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="e.g., Sales Tax">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-1">Rate (%)</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-4 w-4 text-neutral-400" 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>
                                    </div>
                                    <input type="number" name="tax_rate" step="0.01" min="0" max="100" required
                                           class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="8.75">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-neutral-300 mb-1">Jurisdiction</label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <svg class="h-4 w-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" name="tax_jurisdiction"
                                           class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50"
                                           placeholder="e.g., State, Federal">
                                </div>
                            </div>
                            
                            <div class="flex items-center space-x-4">
                                <label class="flex items-center">
                                    <input type="checkbox" name="tax_is_active" checked
                                           class="rounded border-neutral-800 text-neutral-300 focus:ring-neutral-700">
                                    <span class="ml-2 text-sm text-neutral-300">Active</span>
                                </label>
                                
                                <label class="flex items-center">
                                    <input type="checkbox" name="tax_is_compound"
                                           class="rounded border-neutral-800 text-neutral-300 focus:ring-neutral-700">
                                    <span class="ml-2 text-sm text-neutral-300">Compound</span>
                                </label>
                            </div>
                            
                            <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-neutral-50 text-neutral-900 rounded-lg hover:bg-neutral-200 transition-colors duration-200 font-medium text-sm shadow-sm hover:shadow-md">
                                <svg class="w-4 h-4 mr-2" 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 Tax Bracket
                            </button>
                        </form>
                    </div>

                    <!-- Tax Brackets List -->
                    <div class="space-y-2">
                        <?php if ($taxBrackets): ?>
                            <?php foreach ($taxBrackets as $tax): ?>
                                <div class="flex items-center justify-between p-3 border border-neutral-800 rounded-lg hover:bg-neutral-900 transition-colors">
                                    <div class="flex-1">
                                        <div class="flex items-center">
                                            <span class="text-sm font-medium text-neutral-50"><?= h($tax['name']) ?></span>
                                            <?php if (!$tax['is_active']): ?>
                                                <span class="ml-2 px-2 py-1 text-xs rounded-full bg-neutral-800 text-neutral-400">Inactive</span>
                                            <?php endif; ?>
                                            <?php if (($tax['is_compound'] ?? 0)): ?>
                                                <span class="ml-2 px-2 py-1 text-xs rounded-full bg-amber-500/20 border border-amber-500/30 text-amber-200">Compound</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-sm text-neutral-300">
                                            <?= number_format($tax['rate'] * 100, 2) ?>% 
                                            <?php if ($tax['jurisdiction'] ?? ''): ?>· <?= h($tax['jurisdiction']) ?><?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="flex items-center space-x-1">
                                        <button onclick="editTaxBracket(<?= $tax['id'] ?>)" class="p-1.5 text-neutral-400 hover:bg-neutral-800 rounded-lg 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                            </svg>
                                        </button>
                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this tax bracket?')" class="inline">
                                            <input type="hidden" name="action" value="delete_tax_bracket">
                                            <input type="hidden" name="tax_id" value="<?= $tax['id'] ?>">
                                            <button type="submit" class="p-1.5 text-red-400 hover:bg-red-500/10 rounded-lg 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>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-center py-8 text-neutral-400">
                                <svg class="w-12 h-12 mx-auto mb-4 text-neutral-300" 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 class="text-sm">No tax brackets configured</div>
                                <div class="text-xs text-neutral-500 mt-1">Add your first tax bracket to get started</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Tax Bracket Modal -->
    <div id="editTaxModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center">
        <div class="bg-neutral-900 rounded-xl shadow-xl max-w-md w-full mx-4 border border-neutral-800">
            <div class="px-6 py-4 border-b border-neutral-800 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-neutral-50">Edit Tax Bracket</h3>
                <button type="button" onclick="closeEditTaxModal()" class="p-2 text-neutral-400 hover:bg-neutral-800 rounded-lg transition-colors">
                    <svg class="w-5 h-5" 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="p-6">
                <form id="editTaxForm" method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="update_tax_bracket">
                    <input type="hidden" name="tax_id_hidden" id="editTaxId">
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-neutral-300 mb-1">Tax Name</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-4 w-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                                </svg>
                            </div>
                            <input type="text" name="tax_name" id="editTaxName" required
                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-neutral-300 mb-1">Rate (%)</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-4 w-4 text-neutral-400" 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>
                            </div>
                            <input type="number" name="tax_rate" id="editTaxRate" step="0.01" min="0" max="100" required
                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-neutral-300 mb-1">Jurisdiction</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-4 w-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </div>
                            <input type="text" name="tax_jurisdiction" id="editTaxJurisdiction"
                                   class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-neutral-300 mb-1">Description</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-start pt-2 pointer-events-none">
                                <svg class="h-4 w-4 text-neutral-400" 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>
                            <textarea name="tax_description" id="editTaxDescription" rows="3"
                                      class="w-full pl-9 pr-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 placeholder-neutral-500 bg-neutral-950 text-neutral-50 resize-none"></textarea>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-4">
                        <label class="flex items-center">
                            <input type="checkbox" name="tax_is_active" id="editTaxActive"
                                   class="rounded border-neutral-800 text-neutral-300 focus:ring-neutral-700">
                            <span class="ml-2 text-sm text-neutral-300">Active</span>
                        </label>
                        
                        <label class="flex items-center">
                            <input type="checkbox" name="tax_is_compound" id="editTaxCompound"
                                   class="rounded border-neutral-800 text-neutral-300 focus:ring-neutral-700">
                            <span class="ml-2 text-sm text-neutral-300">Compound</span>
                        </label>
                    </div>
                    
                    <div class="flex space-x-3 pt-2">
                        <button type="submit" class="flex-1 inline-flex items-center justify-center px-4 py-2 bg-neutral-50 text-neutral-900 rounded-lg hover:bg-neutral-200 transition-colors duration-200 font-medium text-sm shadow-sm hover:shadow-md">
                            <svg class="w-4 h-4 mr-2" 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>
                            Update Tax Bracket
                        </button>
                        <button type="button" onclick="closeEditTaxModal()" class="flex-1 inline-flex items-center justify-center px-4 py-2 border border-neutral-700 text-neutral-300 hover:bg-neutral-900 rounded-lg transition-colors duration-200 font-medium text-sm">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function addMetaField() {
            const container = document.getElementById('meta-fields');
            const newField = document.createElement('div');
            newField.className = 'flex gap-3 meta-field';
            newField.innerHTML = `
                <div class="relative flex-1">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="h-4 w-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                        </svg>
                    </div>
                    <input type="text" name="meta_label[]" placeholder="Field Label"
                           class="w-full pl-9 pr-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 focus:border-slate-500 text-sm placeholder-slate-400">
                </div>
                <div class="relative flex-1">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="h-4 w-4 text-slate-400" 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>
                    <input type="text" name="meta_value[]" placeholder="Field Data"
                           class="w-full pl-9 pr-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 focus:border-slate-500 text-sm placeholder-slate-400">
                </div>
                <button type="button" onclick="removeMetaField(this)" class="p-2 text-rose-600 hover:bg-rose-50 rounded-lg 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>
            `;
            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;
                
                document.getElementById('editTaxModal').classList.remove('hidden');
            }
        }

        function closeEditModal() {
            document.getElementById('editTaxModal').classList.add('hidden');
        }

        function addPaymentTerm() {
            const container = document.getElementById('payment-terms');
            const newTerm = document.createElement('div');
            newTerm.className = 'flex gap-2 payment-term';
            newTerm.innerHTML = `
                <input type="text" name="custom_payment_terms[]" placeholder="e.g., Net 90, 3% 15, Net 45"
                       class="flex-1 px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 focus:border-slate-500 text-sm placeholder-slate-400">
                <button type="button" onclick="removePaymentTerm(this)" class="p-2 text-rose-600 hover:bg-rose-50 rounded-lg 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="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.classList.remove('hidden');
        }

        function closeLogoModal() {
            document.getElementById('logoModal').classList.add('hidden');
        }

        // 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.innerHTML = '<svg class="w-4 h-4 mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>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('.bg-emerald-50');
            if (existingMessage) {
                existingMessage.remove();
            }
            
            // Create success message
            const messageDiv = document.createElement('div');
            messageDiv.className = 'mb-6 bg-emerald-50 border border-emerald-200 text-emerald-800 px-4 py-3 rounded-lg flex items-center';
            messageDiv.innerHTML = `
                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                </svg>
                ${message}
            `;
            
            // Insert at the top of main content
            const mainContent = document.querySelector('main');
            mainContent.insertBefore(messageDiv, mainContent.firstChild.nextSibling);
            
            // Auto-remove after 3 seconds
            setTimeout(() => {
                messageDiv.remove();
            }, 3000);
        }
        
        function showErrorMessage(message) {
            // Remove any existing messages
            const existingMessage = document.querySelector('.bg-rose-50');
            if (existingMessage) {
                existingMessage.remove();
            }
            
            // Create error message
            const messageDiv = document.createElement('div');
            messageDiv.className = 'mb-6 bg-rose-50 border border-rose-200 text-rose-800 px-4 py-3 rounded-lg flex items-center';
            messageDiv.innerHTML = `
                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                </svg>
                ${message}
            `;
            
            // Insert at the top of main content
            const mainContent = document.querySelector('main');
            mainContent.insertBefore(messageDiv, mainContent.firstChild.nextSibling);
            
            // 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) {
                closeEditModal();
            }
        });

        // 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', {
                    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>
    </div>
</main>

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