<?php
/** @var array $pattern */
/** @var array $certFields */
/** @var array $marksheetFields */
/** @var array $fieldKeys */
/** @var string $csrfToken */

if (!defined('APP_ROOT')) define('APP_ROOT', dirname(dirname(dirname(__DIR__))));

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';

$flash_error = $_SESSION['flash']['error'] ?? '';
$flash_success = $_SESSION['flash']['success'] ?? '';
unset($_SESSION['flash']);

$isLocked   = ($pattern['status'] ?? '') === 'locked';
$pageWidth  = (int)($pattern['page_width']  ?? 595);
$pageHeight = (int)($pattern['page_height'] ?? 842);

$displayScale  = 600 / $pageWidth;
$displayHeight = (int)($pageHeight * $displayScale);

$certBgUrl      = !empty($pattern['cert_background_path'])      ? $pattern['cert_background_path']      . '?t=' . time() : '';
$marksheetBgUrl = !empty($pattern['marksheet_background_path']) ? $pattern['marksheet_background_path'] . '?t=' . time() : '';

$fieldMeta = [
    'student_name'   => ['icon' => 'fa-user',           'color' => '#28a745'],
    'father_name'    => ['icon' => 'fa-user-tag',       'color' => '#28a745'],
    'enrollment_no'  => ['icon' => 'fa-hashtag',        'color' => '#17a2b8'],
    'certificate_no' => ['icon' => 'fa-certificate',    'color' => '#17a2b8'],
    'course'         => ['icon' => 'fa-book',           'color' => '#6f42c1'],
    'branch_name'    => ['icon' => 'fa-building',       'color' => '#6f42c1'],
    'branch_code'    => ['icon' => 'fa-code',           'color' => '#6f42c1'],
    'duration'       => ['icon' => 'fa-clock',          'color' => '#6f42c1'],
    'date_of_issue'  => ['icon' => 'fa-calendar',       'color' => '#fd7e14'],
    'from_date'      => ['icon' => 'fa-calendar-alt',   'color' => '#fd7e14'],
    'to_date'        => ['icon' => 'fa-calendar-check', 'color' => '#fd7e14'],
    'percentage'     => ['icon' => 'fa-percent',        'color' => '#dc3545'],
    'grade'          => ['icon' => 'fa-graduation-cap', 'color' => '#dc3545'],
    'photo'          => ['icon' => 'fa-image',          'color' => '#007bff'],
    'qr_code'        => ['icon' => 'fa-qrcode',         'color' => '#6610f2'],
    'subject_marks'  => ['icon' => 'fa-table',          'color' => '#20c997'],
];
?>
<style>
.pattern-canvas {
    position: relative;
    border: 2px solid #dee2e6;
    background: #f8f9fa;
    margin: 0 auto;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    overflow: hidden;
}
.pattern-canvas img.bg {
    width: 100%;
    height: auto;
    display: block;
    pointer-events: none;
    opacity: 0.85;
}
.field-box {
    position: absolute;
    cursor: move;
    user-select: none;
    border: 2px dashed;
    border-radius: 4px;
    padding: 2px 4px;
    background: rgba(255,255,255,0.85);
    font-size: 11px;
    min-width: 60px;
    min-height: 20px;
    z-index: 10;
    transition: box-shadow 0.15s;
}
.field-box:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    z-index: 20;
}
.field-box.selected {
    border-style: solid;
    border-width: 3px;
    box-shadow: 0 0 0 2px rgba(255,193,7,0.5);
}
.field-box.photo-box { background: rgba(0,123,255,0.15); }
.field-box.qr-box { background: rgba(102,16,242,0.15); }
.field-box.subject-box {
    background: rgba(32,201,151,0.15);
    min-height: 80px;
}
.field-label {
    font-weight: bold;
    pointer-events: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.field-pos {
    font-size: 9px;
    color: #666;
    pointer-events: none;
}
.field-list-item {
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 6px;
    margin-bottom: 4px;
    border: 1px solid #dee2e6;
    transition: all 0.15s;
}
.field-list-item:hover { background: #f0f4ff; }
.field-list-item.active {
    background: #e7f1ff;
    border-color: #007bff;
}
.field-list-item.disabled {
    opacity: 0.5;
    background: #f8f9fa;
}
.tab-content { min-height: 700px; }
</style>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h3 class="mb-1">
                <?= htmlspecialchars($pattern['name'] ?? 'Pattern') ?>
                <?php if ($isLocked): ?>
                    <span class="badge bg-success ms-2"><i class="fas fa-lock"></i> LOCKED</span>
                <?php else: ?>
                    <span class="badge bg-warning text-dark ms-2"><i class="fas fa-pencil"></i> DRAFT</span>
                <?php endif; ?>
            </h3>
            <small class="text-muted">A4 Portrait (<?= $pageWidth ?> × <?= $pageHeight ?> pt) | Drag fields to position | Click "Live Preview" to verify | Use arrow keys to nudge selected field</small>
        </div>
        <div>
            <a href="<?= $bp ?>/super-admin/patterns" class="btn btn-secondary btn-sm">
                <i class="fas fa-arrow-left"></i> Back
            </a>
            <?php if (!$isLocked): ?>
                <button type="button" id="saveBtn" class="btn btn-success btn-sm">
                    <i class="fas fa-save"></i> Save Mapping
                </button>
                <button type="button" id="lockBtn" class="btn btn-danger btn-sm">
                    <i class="fas fa-lock"></i> Lock Pattern
                </button>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($flash_error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($flash_error) ?></div>
    <?php endif; ?>
    <?php if ($flash_success): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= htmlspecialchars($flash_success) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <ul class="nav nav-tabs mb-3" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-cert" type="button">
                <i class="fas fa-certificate"></i> Certificate
                <?php if (!$certBgUrl): ?><span class="badge bg-danger ms-1">No BG</span><?php endif; ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-marksheet" type="button">
                <i class="fas fa-file-alt"></i> Marksheet
                <?php if (!$marksheetBgUrl): ?><span class="badge bg-danger ms-1">No BG</span><?php endif; ?>
            </button>
        </li>
    </ul>

    <form id="mappingForm" method="POST" action="<?= $bp ?>/super-admin/patterns/edit/<?= (int)$pattern['id'] ?>">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '') ?>">
        <div id="hiddenInputs"></div>
    </form>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="tab-cert">
            <?php
            $docType = 'certificate';
            $bgUrl = $certBgUrl;
            $fields = $certFields;
            include __DIR__ . '/_editor_block.php';
            ?>
        </div>
        <div class="tab-pane fade" id="tab-marksheet">
            <?php
            $docType = 'marksheet';
            $bgUrl = $marksheetBgUrl;
            $fields = $marksheetFields;
            include __DIR__ . '/_editor_block.php';
            ?>
        </div>
    </div>
</div>

<script>
const PATTERN_ID = <?= (int)$pattern['id'] ?>;
const BASE_PATH = '<?= $bp ?>';
const PAGE_WIDTH = <?= $pageWidth ?>;
const PAGE_HEIGHT = <?= $pageHeight ?>;
const DISPLAY_SCALE = <?= $displayScale ?>;
const IS_LOCKED = <?= $isLocked ? 'true' : 'false' ?>;
const CSRF_TOKEN = '<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES) ?>';

const FIELD_META = <?= json_encode($fieldMeta) ?>;

let fieldData = {
    certificate: [],
    marksheet: []
};

<?php
$fieldsByType = ['certificate' => $certFields, 'marksheet' => $marksheetFields];
foreach ($fieldsByType as $type => $fields) {
    echo "fieldData.{$type} = [";
    foreach ($fields as $f) {
        echo json_encode([
            'field_key'   => $f['field_key'],
            'label'       => $f['label'],
            'x_pos'       => (float)$f['x_pos'],
            'y_pos'       => (float)$f['y_pos'],
            'font_size'   => (int)$f['font_size'],
            'font_style'  => $f['font_style'],
            'color'       => $f['color'],
            'alignment'   => $f['alignment'],
            'width'       => (float)$f['width'],
            'height'      => (float)$f['height'],
            'border'      => (int)$f['border'],
            'is_enabled'  => (int)$f['is_enabled']
        ]) . ',';
    }
    echo "];\n";
}
?>

let activeDocType = 'certificate';
let selectedFieldIdx = -1;

function renderCanvas(docType) {
    const canvas = document.getElementById('canvas-' + docType);
    if (!canvas) return;

    canvas.querySelectorAll('.field-box').forEach(el => el.remove());

    fieldData[docType].forEach((f, idx) => {
        if (!f.is_enabled) return;

        const box = document.createElement('div');
        box.className = 'field-box';
        if (f.field_key === 'photo') box.classList.add('photo-box');
        if (f.field_key === 'qr_code') box.classList.add('qr-box');
        if (f.field_key === 'subject_marks') box.classList.add('subject-box');

        box.style.borderColor = FIELD_META[f.field_key]?.color || '#000';
        box.style.left = (f.x_pos * DISPLAY_SCALE) + 'px';
        box.style.top  = (f.y_pos * DISPLAY_SCALE) + 'px';

        if (f.field_key === 'photo' || f.field_key === 'qr_code') {
            box.style.width  = ((f.width || 30) * DISPLAY_SCALE) + 'px';
            box.style.height = ((f.height || 30) * DISPLAY_SCALE) + 'px';
        } else if (f.field_key === 'subject_marks') {
            box.style.width = ((f.width || 435) * DISPLAY_SCALE) + 'px';
            box.style.minHeight = '80px';
        } else {
            box.style.width = 'auto';
            box.style.height = 'auto';
        }

        if (idx === selectedFieldIdx && activeDocType === docType) {
            box.classList.add('selected');
        }

        const labelEl = document.createElement('div');
        labelEl.className = 'field-label';
        labelEl.style.fontSize = Math.max(8, (f.font_size || 12) * DISPLAY_SCALE * 0.8) + 'px';
        labelEl.style.color = f.color || '#000';
        labelEl.textContent = f.label || f.field_key;
        box.appendChild(labelEl);

        const posEl = document.createElement('div');
        posEl.className = 'field-pos';
        posEl.textContent = `x:${Math.round(f.x_pos)} y:${Math.round(f.y_pos)}`;
        box.appendChild(posEl);

        if (!IS_LOCKED) {
            makeDraggable(box, idx, docType);
        }

        box.addEventListener('click', (e) => {
            e.stopPropagation();
            selectField(idx, docType);
        });

        canvas.appendChild(box);
    });
}

function makeDraggable(box, idx, docType) {
    let isDragging = false;
    let startX, startY, origX, origY;

    box.addEventListener('mousedown', (e) => {
        if (IS_LOCKED) return;
        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;
        origX = fieldData[docType][idx].x_pos;
        origY = fieldData[docType][idx].y_pos;
        selectField(idx, docType);
        e.preventDefault();
    });

    document.addEventListener('mousemove', (e) => {
        if (!isDragging) return;
        const dx = (e.clientX - startX) / DISPLAY_SCALE;
        const dy = (e.clientY - startY) / DISPLAY_SCALE;
        let newX = origX + dx;
        let newY = origY + dy;
        newX = Math.max(0, Math.min(PAGE_WIDTH - 10, newX));
        newY = Math.max(0, Math.min(PAGE_HEIGHT - 10, newY));
        fieldData[docType][idx].x_pos = newX;
        fieldData[docType][idx].y_pos = newY;
        box.style.left = (newX * DISPLAY_SCALE) + 'px';
        box.style.top  = (newY * DISPLAY_SCALE) + 'px';
        const posEl = box.querySelector('.field-pos');
        if (posEl) posEl.textContent = `x:${Math.round(newX)} y:${Math.round(newY)}`;
        if (selectedFieldIdx === idx) updatePropertyPanel(docType);
    });

    document.addEventListener('mouseup', () => {
        isDragging = false;
    });
}

function selectField(idx, docType) {
    activeDocType = docType;
    selectedFieldIdx = idx;
    renderCanvas(docType);
    updatePropertyPanel(docType);
    document.querySelectorAll('.field-list-item').forEach(el => el.classList.remove('active'));
    const listItem = document.querySelector(`#field-list-${docType} [data-idx="${idx}"]`);
    if (listItem) listItem.classList.add('active');
}

function updatePropertyPanel(docType) {
    const panel = document.getElementById('property-panel-' + docType);
    if (!panel) return;
    if (selectedFieldIdx < 0 || !fieldData[docType][selectedFieldIdx]) {
        panel.innerHTML = '<div class="text-muted text-center py-4"><i class="fas fa-hand-pointer"></i><br>Click a field to edit its properties</div>';
        return;
    }
    const f = fieldData[docType][selectedFieldIdx];
    const meta = FIELD_META[f.field_key] || { color: '#000', icon: 'fa-tag' };

    let sizeInputs = '';
    if (f.field_key === 'photo' || f.field_key === 'qr_code') {
        sizeInputs = `
            <div class="row">
                <div class="col-6">
                    <label class="form-label small">Width (pt)</label>
                    <input type="number" class="form-control form-control-sm prop-input" data-prop="width" value="${f.width || 30}" step="1">
                </div>
                <div class="col-6">
                    <label class="form-label small">Height (pt)</label>
                    <input type="number" class="form-control form-control-sm prop-input" data-prop="height" value="${f.height || 30}" step="1">
                </div>
            </div>`;
    } else if (f.field_key === 'subject_marks') {
        sizeInputs = `
            <div class="mb-2">
                <label class="form-label small">Table Width (pt)</label>
                <input type="number" class="form-control form-control-sm prop-input" data-prop="width" value="${f.width || 435}" step="1">
            </div>`;
    }

    panel.innerHTML = `
        <div class="d-flex align-items-center mb-3">
            <i class="fas ${meta.icon} me-2" style="color: ${meta.color}"></i>
            <strong>${f.label}</strong>
        </div>
        <div class="row mb-2">
            <div class="col-6">
                <label class="form-label small">X (pt)</label>
                <input type="number" class="form-control form-control-sm prop-input" data-prop="x_pos" value="${Math.round(f.x_pos)}" step="1">
            </div>
            <div class="col-6">
                <label class="form-label small">Y (pt)</label>
                <input type="number" class="form-control form-control-sm prop-input" data-prop="y_pos" value="${Math.round(f.y_pos)}" step="1">
            </div>
        </div>
        ${sizeInputs}
        ${f.field_key !== 'photo' && f.field_key !== 'qr_code' ? `
        <div class="row mb-2">
            <div class="col-6">
                <label class="form-label small">Font Size</label>
                <input type="number" class="form-control form-control-sm prop-input" data-prop="font_size" value="${f.font_size}" min="6" max="72">
            </div>
            <div class="col-6">
                <label class="form-label small">Align</label>
                <select class="form-select form-select-sm prop-input" data-prop="alignment">
                    <option value="L" ${f.alignment==='L'?'selected':''}>Left</option>
                    <option value="C" ${f.alignment==='C'?'selected':''}>Center</option>
                    <option value="R" ${f.alignment==='R'?'selected':''}>Right</option>
                </select>
            </div>
        </div>
        <div class="row mb-2">
            <div class="col-6">
                <label class="form-label small">Style</label>
                <select class="form-select form-select-sm prop-input" data-prop="font_style">
                    <option value="regular" ${f.font_style==='regular'?'selected':''}>Regular</option>
                    <option value="bold" ${f.font_style==='bold'?'selected':''}>Bold</option>
                    <option value="italic" ${f.font_style==='italic'?'selected':''}>Italic</option>
                    <option value="bolditalic" ${f.font_style==='bolditalic'?'selected':''}>Bold+Italic</option>
                </select>
            </div>
            <div class="col-6">
                <label class="form-label small">Color</label>
                <input type="color" class="form-control form-control-sm prop-input" data-prop="color" value="${f.color || '#000000'}">
            </div>
        </div>
        ` : ''}
        <div class="form-check mb-2">
            <input type="checkbox" class="form-check-input prop-input" data-prop="border" data-type="checkbox" ${f.border?'checked':''}>
            <label class="form-check-label small">Show Border</label>
        </div>
        <div class="form-check mb-2">
            <input type="checkbox" class="form-check-input prop-input" data-prop="is_enabled" data-type="checkbox" ${f.is_enabled?'checked':''}>
            <label class="form-check-label small">Enabled</label>
        </div>
        <button type="button" class="btn btn-primary btn-sm w-100" onclick="applyPropertyChanges('${docType}')">
            <i class="fas fa-check"></i> Apply Changes
        </button>
        <div class="mt-2 d-flex gap-1">
            <button type="button" class="btn btn-outline-secondary btn-sm flex-fill" onclick="nudgeField('${docType}', -1, 0)" title="Move left 1pt">
                <i class="fas fa-arrow-left"></i>
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm flex-fill" onclick="nudgeField('${docType}', 1, 0)" title="Move right 1pt">
                <i class="fas fa-arrow-right"></i>
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm flex-fill" onclick="nudgeField('${docType}', 0, -1)" title="Move up 1pt">
                <i class="fas fa-arrow-up"></i>
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm flex-fill" onclick="nudgeField('${docType}', 0, 1)" title="Move down 1pt">
                <i class="fas fa-arrow-down"></i>
            </button>
        </div>
        <button type="button" class="btn btn-outline-info btn-sm w-100 mt-2" onclick="previewDocument('${docType}')">
            <i class="fas fa-eye"></i> Live Preview This Layout
        </button>
    `;
}

function nudgeField(docType, dx, dy) {
    if (selectedFieldIdx < 0) return;
    const f = fieldData[docType][selectedFieldIdx];
    f.x_pos = Math.max(0, Math.min(PAGE_WIDTH - 5, f.x_pos + dx));
    f.y_pos = Math.max(0, Math.min(PAGE_HEIGHT - 5, f.y_pos + dy));
    renderCanvas(docType);
    updatePropertyPanel(docType);
}

function applyPropertyChanges(docType) {
    if (selectedFieldIdx < 0) return;
    const f = fieldData[docType][selectedFieldIdx];
    const panel = document.getElementById('property-panel-' + docType);
    if (!panel) return;

    panel.querySelectorAll('.prop-input').forEach(input => {
        const prop = input.getAttribute('data-prop');
        const type = input.getAttribute('data-type');
        let value;
        if (type === 'checkbox') {
            value = input.checked ? 1 : 0;
        } else if (input.type === 'number') {
            value = parseFloat(input.value) || 0;
        } else {
            value = input.value;
        }
        f[prop] = value;
    });

    renderCanvas(docType);
    renderFieldList(docType);
    showToast('Properties applied! Click "Save Mapping" to persist.', 'success');
}

// ===== Keyboard arrow keys to nudge selected field =====
document.addEventListener('keydown', (e) => {
    if (selectedFieldIdx < 0) return;
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT' || e.target.tagName === 'TEXTAREA') return;

    const step = e.shiftKey ? 5 : 1;
    let moved = false;

    if (e.key === 'ArrowLeft')  { nudgeField(activeDocType, -step, 0); moved = true; }
    if (e.key === 'ArrowRight') { nudgeField(activeDocType,  step, 0); moved = true; }
    if (e.key === 'ArrowUp')    { nudgeField(activeDocType, 0, -step); moved = true; }
    if (e.key === 'ArrowDown')  { nudgeField(activeDocType, 0,  step); moved = true; }

    if (moved) e.preventDefault();
});

function renderFieldList(docType) {
    const listEl = document.getElementById('field-list-' + docType);
    if (!listEl) return;
    listEl.innerHTML = '';
    fieldData[docType].forEach((f, idx) => {
        const meta = FIELD_META[f.field_key] || { color: '#000', icon: 'fa-tag' };
        const item = document.createElement('div');
        item.className = 'field-list-item d-flex align-items-center' + (f.is_enabled ? '' : ' disabled');
        item.setAttribute('data-idx', idx);
        item.innerHTML = `
            <i class="fas ${meta.icon} me-2" style="color: ${meta.color}"></i>
            <span class="flex-grow-1">${f.label}</span>
            ${f.is_enabled ? '<i class="fas fa-eye text-success"></i>' : '<i class="fas fa-eye-slash text-muted"></i>'}
        `;
        item.addEventListener('click', () => selectField(idx, docType));
        listEl.appendChild(item);
    });
}

function buildHiddenInputs() {
    const container = document.getElementById('hiddenInputs');
    container.innerHTML = '';
    ['certificate', 'marksheet'].forEach(docType => {
        fieldData[docType].forEach((f, idx) => {
            container.innerHTML += `<input type="hidden" name="${docType}_field_key[]" value="${f.field_key}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_x_pos[]" value="${f.x_pos}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_y_pos[]" value="${f.y_pos}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_font_size[]" value="${f.font_size}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_font_style[]" value="${f.font_style}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_color[]" value="${f.color}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_alignment[]" value="${f.alignment}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_width[]" value="${f.width || 0}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_height[]" value="${f.height || 0}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_border[]" value="${f.border || 0}">`;
            container.innerHTML += `<input type="hidden" name="${docType}_is_enabled[]" value="${f.is_enabled}">`;
        });
    });
}

document.getElementById('saveBtn')?.addEventListener('click', async () => {
    buildHiddenInputs();
    showToast('Saving...', 'info');
    const formData = new FormData(document.getElementById('mappingForm'));
    try {
        const resp = await fetch(BASE_PATH + '/super-admin/patterns/save-ajax/<?= (int)$pattern['id'] ?>', {
            method: 'POST',
            body: formData
        });
        const result = await resp.json();
        if (result.success) {
            showToast('Saved successfully!', 'success');
        } else {
            showToast('Save failed: ' + (result.error || 'Unknown error'), 'error');
        }
    } catch (e) {
        document.getElementById('mappingForm').submit();
    }
});

document.getElementById('lockBtn')?.addEventListener('click', () => {
    if (!confirm('Lock this pattern? After locking, you can clone it to make changes. Existing certificates will use the locked version.')) return;
    buildHiddenInputs();
    const form = document.getElementById('mappingForm');
    const actionInput = document.createElement('input');
    actionInput.type = 'hidden';
    actionInput.name = '_then_lock';
    actionInput.value = '1';
    form.appendChild(actionInput);
    form.submit();
});

function previewDocument(docType) {
    buildHiddenInputs();
    const formData = new FormData(document.getElementById('mappingForm'));
    fetch(BASE_PATH + '/super-admin/patterns/save-ajax/<?= (int)$pattern['id'] ?>', {
        method: 'POST',
        body: formData
    }).then(r => r.json()).then(() => {
        window.open(BASE_PATH + '/super-admin/patterns/preview/<?= (int)$pattern['id'] ?>?doc_type=' + docType, '_blank');
    }).catch(() => {
        window.open(BASE_PATH + '/super-admin/patterns/preview/<?= (int)$pattern['id'] ?>?doc_type=' + docType, '_blank');
    });
}

function showToast(msg, type='info') {
    const colors = { success: 'bg-success', error: 'bg-danger', info: 'bg-info' };
    const toast = document.createElement('div');
    toast.className = `toast show align-items-center text-white ${colors[type] || 'bg-info'} border-0 position-fixed`;
    toast.style.cssText = 'top:20px;right:20px;z-index:9999;min-width:300px;';
    toast.innerHTML = `<div class="d-flex"><div class="toast-body">${msg}</div><button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.parentElement.parentElement.remove()"></button></div>`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}

function uploadBackground(docType) {
    const input = document.getElementById('bg-upload-' + docType);
    if (!input.files[0]) return;
    const formData = new FormData();
    formData.append('background', input.files[0]);
    formData.append('doc_type', docType);
    formData.append('csrf_token', CSRF_TOKEN);

    showToast('Uploading image...', 'info');
    fetch(BASE_PATH + '/super-admin/patterns/upload-background/<?= (int)$pattern['id'] ?>', {
        method: 'POST',
        body: formData
    }).then(r => r.json()).then(data => {
        if (data.success) {
            showToast('Background uploaded!', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Upload failed: ' + (data.error || 'Unknown'), 'error');
        }
    }).catch(e => showToast('Error: ' + e.message, 'error'));
}

function uploadTestPhoto(input) {
    if (!input.files[0]) return;
    const formData = new FormData();
    formData.append('photo', input.files[0]);
    formData.append('csrf_token', CSRF_TOKEN);

    showToast('Uploading test photo...', 'info');
    fetch(BASE_PATH + '/super-admin/patterns/upload-test-photo', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-Token': CSRF_TOKEN,
            'X-Requested-With': 'XMLHttpRequest'
        }
    }).then(r => {
        if (!r.ok) {
            return r.text().then(t => { throw new Error(t); });
        }
        return r.json();
    }).then(data => {
        if (data.success) {
            showToast('Test photo uploaded! Click "Live Preview" to see it.', 'success');
        } else {
            showToast('Upload failed: ' + (data.error || 'Unknown'), 'error');
        }
    }).catch(e => {
        showToast('Error: ' + e.message.substring(0, 100), 'error');
    });
    input.value = '';
}

function clearTestPhoto() {
    if (!confirm('Clear test photo?')) return;
    fetch(BASE_PATH + '/super-admin/patterns/clear-test-photo', {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    }).then(r => r.json()).then(data => {
        if (data.success) {
            showToast('Test photo cleared. Preview will show placeholder.', 'info');
        }
    }).catch(e => showToast('Error: ' + e.message, 'error'));
}

document.querySelectorAll('[data-bs-toggle="tab"]').forEach(btn => {
    btn.addEventListener('shown.bs.tab', (e) => {
        const target = e.target.getAttribute('data-bs-target');
        if (target === '#tab-cert') {
            activeDocType = 'certificate';
        } else if (target === '#tab-marksheet') {
            activeDocType = 'marksheet';
        }
    });
});

document.addEventListener('DOMContentLoaded', () => {
    renderCanvas('certificate');
    renderFieldList('certificate');
    renderCanvas('marksheet');
    renderFieldList('marksheet');

    document.querySelectorAll('.pattern-canvas').forEach(canvas => {
        canvas.addEventListener('click', (e) => {
            if (e.target === canvas || e.target.tagName === 'IMG') {
                selectedFieldIdx = -1;
                renderCanvas(activeDocType);
                updatePropertyPanel(activeDocType);
            }
        });
    });
});
</script>
