<?php
if (isset($_GET['saved'])) {
    pjUtil::printNotice('Saved', 'Invoice template changes have been saved.');
}

$settings = isset($tpl['settings']) ? $tpl['settings'] : array();
$template = isset($tpl['template_html']) ? $tpl['template_html'] : '';
$locales  = isset($tpl['locale_arr']) ? $tpl['locale_arr'] : array();
$lblLoc   = isset($tpl['labels_by_locale']) ? $tpl['labels_by_locale'] : array();

$chk = function ($arr, $key) {
    if (!isset($arr[$key])) return '';
    return !empty($arr[$key]) ? ' checked="checked"' : '';
};

// Labels grouped per section for the floating sidebar.
$labelGroups = array(
    'visibility' => array(
        'label'  => 'Visibility',
        'icon'   => 'fa-th-list',
    ),
    'metadata' => array(
        'label'  => 'Title &amp; metadata',
        'icon'   => 'fa-hashtag',
        'fields' => array(
            'title'                => 'Page title',
            'label_invoice_number' => 'Invoice number',
            'label_issue_date'     => 'Issue date',
            'label_due_date'       => 'Due date',
            'label_order_number'   => 'Order number',
            'label_status'         => 'Status',
        ),
    ),
    'customer' => array(
        'label'  => 'Customer details',
        'icon'   => 'fa-user',
        'fields' => array(
            'label_billing'        => 'Header: Billing address',
            'label_shipping'       => 'Header: Shipping address',
            'label_coc_number'     => 'Customer COC number',
        ),
    ),
    'items' => array(
        'label'  => 'Items table',
        'icon'   => 'fa-list',
        'fields' => array(
            'col_description'      => 'Column: Description',
            'col_qty'              => 'Column: Qty',
            'col_unit_price'       => 'Column: Price',
            'col_line_total'       => 'Column: Total',
        ),
    ),
    'totals' => array(
        'label'  => 'Financial',
        'icon'   => 'fa-calculator',
        'fields' => array(
            'label_subtotal'       => 'Subtotal',
            'label_discount'       => 'Discount',
            'label_shipping_cost'  => 'Shipping',
            'label_tax'            => 'Tax',
            'label_total'          => 'Total',
        ),
    ),
    'footer' => array(
        'label'  => 'Statuses &amp; footer',
        'icon'   => 'fa-flag',
        'fields' => array(
            'status_paid'          => 'Status: Paid',
            'status_not_paid'      => 'Status: Unpaid',
            'status_cancelled'     => 'Status: Cancelled',
            'payment_title'        => 'Payment instructions title',
            'payment_text'         => 'Payment instructions text',
            'footer_note'          => 'Footer note',
        ),
    ),
);

// Default locale ID
$default_locale_id = 0;
foreach ($locales as $loc) {
    if ((int) $loc['is_default'] === 1) { $default_locale_id = (int) $loc['id']; break; }
}
// Actieve locale: uit query string, anders default
$active_locale_id = isset($_GET['lang']) ? (int) $_GET['lang'] : $default_locale_id;
$has_active = false;
foreach ($locales as $loc) { if ((int) $loc['id'] === $active_locale_id) { $has_active = true; break; } }
if (!$has_active) { $active_locale_id = $default_locale_id; }
?>
<style>
/* Main Page Layout Wrapper */
.inv-tpl-page { 
    max-width: 1200px; 
    margin: 0 left; 
    padding: 10px 20px 40px 20px;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.inv-tpl-page .page-heading { 
    border-bottom: 1px solid var(--admin-card-border, #e5e7eb); 
    padding: 15px 0; 
    margin-bottom: 20px; 
}
.inv-tpl-page .page-heading h2 { margin: 0; font-weight: 700; font-size: 22px; color: var(--admin-heading-text, #1f2937); }
.inv-tpl-page .page-heading p { margin: 6px 0 0; color: var(--admin-muted-text, #6b7280); font-size: 13px; }
.inv-tpl-page .page-heading .fa { color: var(--admin-primary, #f97316); margin-right: 4px; }

/* Flexbox Workspace Grid */
.inv-tpl-workspace {
    display: flex;
    gap: 25px;
    align-items: flex-start;
    position: relative;
}

/* Fixed Width Column for Sidebar */
.inv-tpl-sidebar-wrapper {
    flex: 0 0 240px;
    position: sticky;
    top: 20px;
    z-index: 10;
}

/* Form Settings Layout Area */
.inv-tpl-content-form {
    flex: 1;
    min-width: 0; /* Prevents flexbox container bursting items */
}

/* Sidebar Custom Styling Refinements */
#invoice-tpl-sidebar {
    background: var(--admin-card-bg-solid, #fff);
    border: 1px solid var(--admin-card-border, #e5e7eb);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    padding: 12px;
    width: 100%;
    box-sizing: border-box;
}
#invoice-tpl-sidebar .adm-sidebar-search { margin: 4px 0 10px 0; }
#invoice-tpl-sidebar .adm-sidebar-search-input { 
    width: 100%; 
    padding: 6px 10px; 
    font-size: 13px; 
    border: 1px solid var(--admin-input-border, #d1d5db); 
    border-radius: 6px;
    box-sizing: border-box;
}
#invoice-tpl-sidebar .adm-nav-items { list-style: none; padding: 0; margin: 0; }
#invoice-tpl-sidebar .adm-sidebar-item { 
    display: block; 
    padding: 8px 10px; 
    font-size: 13px; 
    color: var(--admin-main-text, #4b5563); 
    text-decoration: none; 
    border-radius: 6px; 
    cursor: pointer;
    margin-bottom: 2px;
    transition: all 0.15s ease;
}
#invoice-tpl-sidebar .adm-sidebar-item:hover, 
#invoice-tpl-sidebar .adm-sidebar-item.active { 
    background: var(--admin-table-row-hover, #f3f4f6); 
    color: var(--admin-primary, #f97316); 
    font-weight: 600; 
}

/* Configuration Panels */
.sc-section { 
    border-left: 4px solid var(--admin-primary, #f97316); 
    padding: 16px 20px; 
    margin-bottom: 20px; 
    background: var(--admin-card-bg-solid, #fff); 
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    border-top: 1px solid var(--admin-card-border, #e5e7eb); 
    border-right: 1px solid var(--admin-card-border, #e5e7eb); 
    border-bottom: 1px solid var(--admin-card-border, #e5e7eb); 
}
.sc-section h4 { 
    margin: 0 0 14px 0; 
    color: var(--admin-primary, #f97316); 
    font-size: 12px; 
    font-weight: 700; 
    text-transform: uppercase; 
    letter-spacing: 0.7px; 
    border-bottom: 1px dashed var(--admin-card-border, #e5e7eb);
    padding-bottom: 6px;
}
.sc-section .sc-check-row { display: flex; flex-wrap: wrap; gap: 10px 20px; font-size: 13px; color: var(--admin-main-text, #374151); }
.sc-section .sc-check-row label { margin: 0; font-weight: 400; cursor: pointer; user-select: none; display: flex; align-items: center; gap: 6px; }
.sc-section .sc-check-row input[type=checkbox] { margin: 0; width: 15px; height: 15px; vertical-align: middle; }
.sc-section .help { font-size: 11px; color: var(--admin-muted-text, #9ca3af); margin-top: 6px; italic; }

/* Grid Aligned Input Fields */
.sc-lbl-row { display: flex; align-items: center; gap: 15px; margin-bottom: 10px; }
.sc-lbl-row label { flex: 0 0 180px; font-size: 13px; color: var(--admin-main-text, #4b5563); margin: 0; font-weight: 500; text-align: left; }
.sc-lbl-row .form-control { flex: 1; padding: 7px 12px; font-size: 13px; height: auto; border: 1px solid var(--admin-input-border, #d1d5db); border-radius: 4px; }
.sc-lbl-row textarea.form-control { resize: vertical; min-height: 60px; line-height: 1.5; }

/* Defaults Action Bar Banner */
.sc-defaults-bar { 
    display: flex; 
    align-items: center; 
    gap: 12px; 
    padding: 12px 16px; 
    background: var(--admin-primary-lighter, #fff8f2); 
    border-left: 4px solid var(--admin-primary, #f97316); 
    border-radius: 4px; 
    margin-bottom: 20px; 
    font-size: 13px;
    border-top: 1px solid var(--admin-primary-light, #ffedd5);
    border-right: 1px solid var(--admin-primary-light, #ffedd5);
    border-bottom: 1px solid var(--admin-primary-light, #ffedd5);
}
.sc-defaults-bar .fa {
    color: var(--admin-primary, #f97316) !important;
}
.sc-defaults-bar .flex1 { flex: 1; cursor: pointer; color: var(--admin-primary-dark, #c2410c); }
.sc-defaults-bar .fa { color: var(--admin-primary, #f97316); margin-right: 4px; }
.sc-defaults-bar .overrule { white-space: nowrap; font-size: 13px; margin: 0; cursor: pointer; display: flex; align-items: center; gap: 4px; }

/* Advanced Template Block */
.sc-template-editor { font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 1.6; padding: 12px; border: 1px solid var(--admin-input-border, #d1d5db); border-radius: 4px; width: 100%; background: var(--admin-input-bg, #f9fafb); resize: vertical; box-sizing: border-box; }

/* Bottom Action Footer Fixes */
.sc-footer-bar { 
    position: sticky; 
    bottom: 0; 
    padding: 16px 20px; 
    background: #fff; 
    border-top: 1px solid #e5e7eb; 
    display: flex; 
    gap: 12px; 
    justify-content: flex-end; 
    margin: 30px -20px -20px -20px; 
    box-shadow: 0 -4px 12px rgba(0,0,0,0.05); 
    z-index: 20; 
}
.sc-footer-bar .btn { border-radius: 6px; padding: 8px 20px; font-weight: 500; font-size: 13px; }

/* Native Layout Adjustments for Tablet views */
@media (max-width: 850px) {
    .inv-tpl-workspace { flex-direction: column; }
    .inv-tpl-sidebar-wrapper { flex: 1 1 100%; width: 100%; position: relative; top: 0; }
}
</style>

<div class="inv-tpl-page">
    <div class="page-heading">
        <h2><i class="fa fa-file-text-o"></i> Invoice template</h2>
        <p>Company details &amp; logo are managed on <a href="<?php echo PJ_INSTALL_URL; ?>index.php?controller=pjAdminProfile&amp;action=pjActionIndex">Profile</a>. Colors are managed on <a href="<?php echo PJ_INSTALL_URL; ?>index.php?controller=pjAdminOptions&amp;action=pjActionPreview">Theme &amp; Colors</a>.</p>
    </div>

    <div class="inv-tpl-workspace">
        
        <div class="inv-tpl-sidebar-wrapper">
            </div>

        <div class="inv-tpl-content-form">
            <form action="<?php echo PJ_INSTALL_URL; ?>index.php?controller=pjAdminOptions&amp;action=pjActionInvoiceTemplate" method="post" id="frmInvoiceTemplate">
			<input type="hidden" name="csrf_token" value="<?php echo pjAppController::getCsrfToken(); ?>">
                <input type="hidden" name="save_template_post" value="1" />
                <input type="hidden" name="active_locale" id="active_locale_input" value="<?php echo (int) $active_locale_id; ?>" />

                <div class="sc-defaults-bar">
                    <div id="btnFillDefaults" class="flex1">
                        <i class="fa fa-magic"></i>
                        <strong>Fill default labels</strong>
                        <span class="text-muted"> &mdash; all labels in one click</span>
                    </div>
                    <label class="overrule" title="Overwrite fields that already have values">
                        <input type="checkbox" id="chkOverwriteDefaults"> Overwrite
                    </label>
                </div>

                <div class="sc-section" id="section-visibility" data-section="visibility">
                    <h4><i class="fa fa-th-list"></i> Visibility</h4>

                    <div style="margin-bottom:16px;">
                        <div style="font-weight:600; font-size:13px; margin-bottom:6px; color:#1f2937;">Metadata block</div>
                        <div class="sc-check-row">
                            <label><input type="checkbox" name="settings[show_metadata][number]" value="1"<?php echo $chk(@$settings['show_metadata'], 'number'); ?>> Invoice number</label>
                            <label><input type="checkbox" name="settings[show_metadata][issue_date]" value="1"<?php echo $chk(@$settings['show_metadata'], 'issue_date'); ?>> Issue date</label>
                            <label><input type="checkbox" name="settings[show_metadata][due_date]" value="1"<?php echo $chk(@$settings['show_metadata'], 'due_date'); ?>> Due date</label>
                            <label><input type="checkbox" name="settings[show_metadata][status]" value="1"<?php echo $chk(@$settings['show_metadata'], 'status'); ?>> Status</label>
                            <label><input type="checkbox" name="settings[show_metadata][order_number]" value="1"<?php echo $chk(@$settings['show_metadata'], 'order_number'); ?>> Order number</label>
                        </div>
                    </div>

                    <div style="margin-bottom:16px;">
                        <div style="font-weight:600; font-size:13px; margin-bottom:6px; color:#1f2937;">Customer details</div>
                        <div class="sc-check-row">
                            <label><input type="checkbox" name="settings[show_customer][billing]" value="1"<?php echo $chk(@$settings['show_customer'], 'billing'); ?>> Billing address</label>
                            <label><input type="checkbox" name="settings[show_customer][shipping]" value="1"<?php echo $chk(@$settings['show_customer'], 'shipping'); ?>> Shipping address</label>
                            <label><input type="checkbox" name="settings[show_customer][coc_number]" value="1"<?php echo $chk(@$settings['show_customer'], 'coc_number'); ?>> COC number</label>
                        </div>
                        <div class="help">Shipping address is hidden automatically when it is not available.</div>
                    </div>

                    <div style="margin-bottom:16px;">
                        <div style="font-weight:600; font-size:13px; margin-bottom:6px; color:#1f2937;">Items table</div>
                        <div class="sc-check-row">
                            <label><input type="checkbox" name="settings[show_items_columns][image]" value="1"<?php echo $chk(@$settings['show_items_columns'], 'image'); ?>> Image</label>
                            <label><input type="checkbox" name="settings[show_items_columns][description]" value="1"<?php echo $chk(@$settings['show_items_columns'], 'description'); ?>> Description</label>
                            <label><input type="checkbox" name="settings[show_items_columns][qty]" value="1"<?php echo $chk(@$settings['show_items_columns'], 'qty'); ?>> Qty</label>
                            <label><input type="checkbox" name="settings[show_items_columns][unit_price]" value="1"<?php echo $chk(@$settings['show_items_columns'], 'unit_price'); ?>> Unit price</label>
                            <label><input type="checkbox" name="settings[show_items_columns][line_total]" value="1"<?php echo $chk(@$settings['show_items_columns'], 'line_total'); ?>> Line total</label>
                        </div>
                    </div>

                    <div style="margin-bottom:16px;">
                        <div style="font-weight:600; font-size:13px; margin-bottom:6px; color:#1f2937;">Financial overview</div>
                        <div class="sc-check-row">
                            <label><input type="checkbox" name="settings[show_totals][subtotal]" value="1"<?php echo $chk(@$settings['show_totals'], 'subtotal'); ?>> Subtotal</label>
                            <label><input type="checkbox" name="settings[show_totals][discount]" value="1"<?php echo $chk(@$settings['show_totals'], 'discount'); ?>> Discount</label>
                            <label><input type="checkbox" name="settings[show_totals][shipping]" value="1"<?php echo $chk(@$settings['show_totals'], 'shipping'); ?>> Shipping</label>
                            <label><input type="checkbox" name="settings[show_totals][tax]" value="1"<?php echo $chk(@$settings['show_totals'], 'tax'); ?>> Tax</label>
                            <label><input type="checkbox" name="settings[show_totals][total]" value="1"<?php echo $chk(@$settings['show_totals'], 'total'); ?>> Total</label>
                        </div>
                    </div>

                    <div>
                        <div style="font-weight:600; font-size:13px; margin-bottom:6px; color:#1f2937;">Other sections</div>
                        <div class="sc-check-row" style="flex-direction:column; gap:6px;">
                            <label><input type="checkbox" name="settings[show_payment_instructions]" value="1"<?php echo !empty($settings['show_payment_instructions']) ? ' checked="checked"' : ''; ?>> Payment instructions for unpaid invoices</label>
                            <label><input type="checkbox" name="settings[show_footer_notes]" value="1"<?php echo !empty($settings['show_footer_notes']) ? ' checked="checked"' : ''; ?>> Footer note / notes</label>
                        </div>
                    </div>
                </div>

                <div class="tab-content">
                    <?php foreach ($locales as $loc):
                        $vals   = isset($lblLoc[$loc['id']]) ? $lblLoc[$loc['id']] : array();
                        $active = ((int) $loc['id'] === $active_locale_id) ? ' active' : '';
                    ?>
                    <div role="tabpanel" class="tab-pane<?php echo $active; ?>" id="lblTab<?php echo $loc['id']; ?>" data-locale="<?php echo $loc['language_iso']; ?>" data-locale-id="<?php echo (int) $loc['id']; ?>">

                        <?php foreach ($labelGroups as $gKey => $group):
                            if ($gKey === 'visibility') continue;
                        ?>
                        <div class="sc-section" id="section-<?php echo $gKey; ?>-<?php echo $loc['id']; ?>" data-section="<?php echo $gKey; ?>">
                            <h4><i class="fa <?php echo $group['icon']; ?>"></i> <?php echo $group['label']; ?></h4>
                            <?php foreach ($group['fields'] as $field => $desc):
                                $v = isset($vals[$field]) ? $vals[$field] : '';
                                $isLong = ($field === 'payment_text' || $field === 'footer_note');
                            ?>
                            <div class="sc-lbl-row">
                                <label><?php echo htmlspecialchars(strip_tags($desc)); ?></label>
                                <?php if ($isLong): ?>
                                    <textarea name="i18n[<?php echo $loc['id']; ?>][<?php echo $field; ?>]" class="form-control lbl-field" data-field="<?php echo $field; ?>" rows="2"><?php echo htmlspecialchars($v); ?></textarea>
                                <?php else: ?>
                                    <input type="text" name="i18n[<?php echo $loc['id']; ?>][<?php echo $field; ?>]" value="<?php echo htmlspecialchars($v); ?>" class="form-control lbl-field" data-field="<?php echo $field; ?>">
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endforeach; ?>

                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="sc-section" id="section-advanced" data-section="advanced" style="border-left-color:#6b7280;">
                    <h4 style="color:#6b7280; cursor:pointer;" onclick="document.getElementById('advBody').style.display = document.getElementById('advBody').style.display === 'none' ? 'block' : 'none';">
                        <i class="fa fa-code"></i> Base HTML template (advanced) <i class="fa fa-chevron-down" style="float:right;"></i>
                    </h4>
                    <div id="advBody" style="display:none;">
                        <div style="display:flex; gap:12px; flex-wrap:wrap;">
                            <div style="flex:1 1 400px; min-width:320px;">
                                <textarea name="invoice_template" id="invoice_template" class="sc-template-editor" rows="18"><?php echo htmlspecialchars($template); ?></textarea>
                                <div style="margin-top:8px; display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                                    <button type="button" class="btn btn-default btn-xs" id="btnResetTemplate"><i class="fa fa-undo"></i> Restore default template</button>
                                    <label style="margin:0; font-size:12px;">
                                        <input type="checkbox" name="settings[raw_html_mode]" value="1"<?php echo !empty($settings['raw_html_mode']) ? ' checked="checked"' : ''; ?>>
                                        RAW HTML mode
                                    </label>
                                </div>
                            </div>
                            <div style="flex:0 0 200px; background: #fafafa; border:1px solid #e5e7eb; border-radius:6px; padding:10px; font-size:11px; line-height:1.7;">
                                <strong style="display:block; margin-bottom:6px; font-size:12px;">Available tokens</strong>
                                <div style="color:#6b7280; margin-bottom:4px;">Invoice:</div>
                                <code>{uuid}</code> <code>{order_id}</code> <code>{issue_date}</code> <code>{due_date}</code> <code>{status}</code><br>
                                <div style="color:#6b7280; margin:6px 0 4px;">Company:</div>
                                <code>{CompanyLogo}</code> <code>{CompanyName}</code> <code>{CompanyAddress}</code> <code>{CompanyZip}</code> <code>{CompanyCity}</code> <code>{CompanyCountry}</code> <code>{CompanyState}</code> <code>{CompanyPhone}</code> <code>{CompanyEmail}</code> <code>{CompanyUrl}</code><br>
                                <div style="color:#6b7280; margin:6px 0 4px;">Customer:</div>
                                <code>{b_name}</code> <code>{b_address_1}</code> <code>{b_zip}</code> <code>{b_city}</code> <code>{b_country}</code> <code>{s_name}</code> <code>{s_address_1}</code> <code>{s_zip}</code> <code>{s_city}</code> <code>{s_country}</code><br>
                                <div style="color:#6b7280; margin:6px 0 4px;">Totals:</div>
                                <code>{items}</code> <code>{price}</code> <code>{discount}</code> <code>{shipping}</code> <code>{tax}</code> <code>{insurance}</code> <code>{total}</code> <code>{notes}</code>
                                <hr style="margin:8px 0;">
                                <small style="color:#9ca3af;">Click a token to insert it.</small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="sc-footer-bar">
                    <a id="btnPreviewInvoice" href="<?php echo PJ_INSTALL_URL; ?>index.php?controller=pjAdminOptions&amp;action=pjActionPreviewInvoiceTemplate&amp;lang=<?php echo (int) $active_locale_id; ?>" target="_blank" class="btn btn-default btn-sm">
                        <i class="fa fa-eye"></i> Preview (PDF)
                    </a>
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="fa fa-save"></i> Save
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript">
(function() {
    var defaults = {
        'nl-NL': <?php echo json_encode(pjAppController::getInvoiceVariantDefaults('nl-NL')); ?>,
        'en-GB': <?php echo json_encode(pjAppController::getInvoiceVariantDefaults('en-GB')); ?>,
        'de-DE': <?php echo json_encode(pjAppController::getInvoiceVariantDefaults('de-DE')); ?>
    };

    function getActiveLocale() {
        var active = document.querySelector('.tab-pane.active');
        if (!active) return 'en-GB';
        return active.getAttribute('data-locale') || 'en-GB';
    }

    document.getElementById('btnFillDefaults').addEventListener('click', function() {
        var lang = getActiveLocale();
        if (!defaults[lang]) return;
        var force = document.getElementById('chkOverwriteDefaults').checked;
        var filled = 0;
        var activePane = document.querySelector('.tab-pane.active');
        if (!activePane) return;
        activePane.querySelectorAll('.lbl-field').forEach(function(el) {
            var f = el.getAttribute('data-field');
            if (!defaults[lang][f]) return;
            if (force || !el.value.trim()) {
                el.value = defaults[lang][f];
                el.style.backgroundColor = '#fef3e2';
                setTimeout(function() { el.style.backgroundColor = ''; }, 1500);
                filled++;
            }
        });
        if (filled === 0) {
            alert('No empty fields found. Check "Overwrite" to replace existing values.');
        }
    });

    document.querySelectorAll('#advBody code').forEach(function(c) {
        c.style.cursor = 'pointer';
        c.title = 'Click to insert in the editor';
        c.addEventListener('click', function() {
            var token = c.textContent.replace(/\*$/, '').trim();
            var ta = document.getElementById('invoice_template');
            if (!ta) return;
            var start = ta.selectionStart, end = ta.selectionEnd, v = ta.value;
            ta.value = v.substring(0, start) + token + v.substring(end);
            ta.selectionStart = ta.selectionEnd = start + token.length;
            ta.focus();
            var orig = c.style.background;
            c.style.background = '#fef3e2';
            setTimeout(function() { c.style.background = orig; }, 600);
        });
    });

    var btnReset = document.getElementById('btnResetTemplate');
    if (btnReset) {
        btnReset.addEventListener('click', function(e) {
            e.preventDefault();
            if (!confirm('Remove the custom template and restore the default?')) return;
            fetch('<?php echo PJ_INSTALL_URL; ?>index.php?controller=pjAdminOptions&action=pjActionResetInvoiceTemplate', {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function(r) { return r.json(); })
            .then(function(d) {
                if (d && d.status === 'OK') { location.reload(); }
                else { alert('Error: ' + (d && d.text ? d.text : 'unknown')); }
            })
            .catch(function(e) { alert('Error: ' + e); });
        });
    }

    // Modern layout sidebar creation code
    function buildSidebar() {
        var sb = document.createElement('div');
        sb.id = 'invoice-tpl-sidebar';

        var html = '';

        <?php if (!empty($tpl['is_flag_ready']) && !empty($locales)): ?>
        html += '<div style="display:flex;gap:4px;padding-bottom:10px;border-bottom:1px solid #eee;margin-bottom:10px;">';
        <?php foreach ($locales as $v):
            $active = ((int) $v['id'] === $active_locale_id) ? 'btn-primary' : 'btn-white';
        ?>
        html += '<button type="button" class="btn btn-xs <?php echo $active; ?> sc-sidebar-lang-btn" data-locale-id="<?php echo (int) $v['id']; ?>" style="flex:1;padding:4px 2px;">'
            + '<img src="<?php echo PJ_INSTALL_URL . PJ_FRAMEWORK_LIBS_PATH . 'pj/img/flags/' . $v['file']; ?>" alt="<?php echo pjSanitize::html($v['name']); ?>" style="height:12px;vertical-align:middle;">'
            + '</button>';
        <?php endforeach; ?>
        html += '</div>';
        <?php endif; ?>

        html += '<div class="adm-sidebar-search"><input type="text" class="adm-sidebar-search-input" placeholder="Search section..."></div>';
        html += '<div class="adm-sidebar-content">';
        var navItems = [
            { key: 'visibility', label: 'Visibility', icon: 'fa-th-list' },
            { key: 'metadata',   label: 'Title & metadata', icon: 'fa-hashtag' },
            { key: 'customer',   label: 'Customer details', icon: 'fa-user' },
            { key: 'items',      label: 'Items table', icon: 'fa-list' },
            { key: 'totals',     label: 'Financial', icon: 'fa-calculator' },
            { key: 'footer',     label: 'Statuses & footer', icon: 'fa-flag' },
            { key: 'advanced',   label: 'Advanced (HTML)', icon: 'fa-code' }
        ];
        html += '<ul class="adm-nav-items">';
        navItems.forEach(function(it, i) {
            html += '<li><a class="adm-sidebar-item sc-sidebar-nav-item' + (i === 0 ? ' active' : '') + '" data-nav-key="' + it.key + '">'
                + '<i class="fa ' + it.icon + '" style="width:14px;color:var(--admin-primary, #f97316);"></i> ' + it.label + '</a></li>';
        });
        html += '</ul></div>';

        sb.innerHTML = html;
        
        // Append inside our structural wrapper grid instead of global DOM body root
        var targetWrapper = document.querySelector('.inv-tpl-sidebar-wrapper');
        if (targetWrapper) {
            targetWrapper.appendChild(sb);
        }

        sb.querySelectorAll('.sc-sidebar-lang-btn').forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                var lid = btn.getAttribute('data-locale-id');
                document.querySelectorAll('.tab-pane').forEach(function(p) {
                    p.classList.toggle('active', p.id === 'lblTab' + lid);
                });
                sb.querySelectorAll('.sc-sidebar-lang-btn').forEach(function(b) {
                    b.classList.toggle('btn-primary', b === btn);
                    b.classList.toggle('btn-white', b !== btn);
                });
                var hidden = document.getElementById('active_locale_input');
                if (hidden) hidden.value = lid;
                var prevBtn = document.getElementById('btnPreviewInvoice');
                if (prevBtn) {
                    prevBtn.href = '<?php echo PJ_INSTALL_URL; ?>index.php?controller=pjAdminOptions&action=pjActionPreviewInvoiceTemplate&lang=' + lid;
                }
            });
        });

        sb.querySelectorAll('.sc-sidebar-nav-item').forEach(function(navBtn) {
            navBtn.addEventListener('click', function(e) {
                e.preventDefault();
                var key = navBtn.getAttribute('data-nav-key');

                sb.querySelectorAll('.sc-sidebar-nav-item').forEach(function(b) { b.classList.remove('active'); });
                navBtn.classList.add('active');

                var target = null;
                if (key === 'visibility') {
                    target = document.getElementById('section-visibility');
                } else if (key === 'advanced') {
                    target = document.getElementById('section-advanced');
                    var adv = document.getElementById('advBody');
                    if (adv) adv.style.display = 'block';
                } else {
                    var activePane = document.querySelector('.tab-pane.active');
                    if (activePane) {
                        target = activePane.querySelector('[data-section="' + key + '"]');
                    }
                    if (!target) {
                        target = document.querySelector('[data-section="' + key + '"]');
                    }
                }

                if (target) {
                    var rect = target.getBoundingClientRect();
                    var offset = window.pageYOffset + rect.top - 20;
                    window.scrollTo({ top: offset, behavior: 'smooth' });
                }
            });
        });

        var searchInput = sb.querySelector('.adm-sidebar-search-input');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                var q = searchInput.value.toLowerCase().trim();
                sb.querySelectorAll('.sc-sidebar-nav-item').forEach(function(item) {
                    var label = item.textContent.toLowerCase();
                    item.closest('li').style.display = (!q || label.indexOf(q) !== -1) ? '' : 'none';
                });
            });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', buildSidebar);
    } else {
        buildSidebar();
    }
})();
</script>
