<?php
/**
 * Super Admin — Template Details + Drag-and-Drop Field Position Editor
 *
 * Shows the uploaded JPG template with draggable field overlays.
 * Super Admin can:
 *   1. Add fields from a dropdown (student_name, enrollment_no, etc.)
 *   2. Drag fields to reposition them on the image
 *   3. Edit font size, color, alignment per field
 *   4. Click "Save All Positions" to persist changes via AJAX
 *
 * Coordinates are stored in POINTS (PDF coordinate system).
 * The image is displayed at its natural size (or scaled to fit container).
 * Pixel positions are converted to point positions using the scale factor.
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$template = $template ?? [];
$fields = $fields ?? [];
$fieldKeys = $fieldKeys ?? [];

$bgUrl = '';
if (!empty($template['background_image'])) {
    $bgUrl = $bp . '/' . htmlspecialchars($template['background_image'], ENT_QUOTES, 'UTF-8');
}
$tw = (int) ($template['template_width'] ?? 842);
$th = (int) ($template['template_height'] ?? 595);

$typeLabels = [
    'certificate' => 'Certificate', 'marksheet' => 'Marksheet', 'affiliation' => 'Affiliation',
    'authorization' => 'Authorization', 'renewal' => 'Renewal Letter',
    'franchise_agreement' => 'Franchise Agreement', 'id_card' => 'ID Card', 'admit_card' => 'Admit Card',
];
?>
<div class="admin-section">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px;">
        <a href="<?= $bp ?>/super-admin/certificate-templates" style="color:#6c3fe8;text-decoration:none;font-size:0.85rem;">← Back to Templates</a>
        <div style="display:flex;gap:8px;">
            <a href="<?= $bp ?>/super-admin/certificate-templates/<?= (int) ($template['id'] ?? 0) ?>/edit" class="admin-btn" style="background:#f39c12;color:#fff;text-decoration:none;padding:8px 16px;border-radius:6px;font-size:0.82rem;font-weight:600;">Edit Template</a>
        </div>
    </div>

    <!-- Template Info -->
    <div class="admin-card" style="background:linear-gradient(135deg,#6c3fe8,#4a2db8);color:#fff;border-radius:12px;padding:20px;margin-bottom:20px;">
        <h2 style="margin:0;font-size:1.2rem;"><?= htmlspecialchars($template['name'] ?? '', ENT_QUOTES, 'UTF-8') ?></h2>
        <p style="margin:4px 0 0;opacity:0.9;font-size:0.85rem;">
            Type: <strong><?= htmlspecialchars($typeLabels[$template['type']] ?? $template['type'], ENT_QUOTES, 'UTF-8') ?></strong>
            · Course: <strong><?= htmlspecialchars($template['course_name'] ?? 'All Courses', ENT_QUOTES, 'UTF-8') ?></strong>
            · Size: <?= $tw ?>×<?= $th ?>pt
            · <?= count($fields) ?> field(s)
            · <span id="saveStatus" style="background:rgba(255,255,255,0.2);padding:2px 10px;border-radius:10px;font-size:0.76rem;">All changes saved</span>
        </p>
    </div>

    <div style="display:grid;grid-template-columns:1fr 340px;gap:20px;">

        <!-- LEFT: Drag-and-Drop Canvas -->
        <div class="admin-card" style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <h3 style="margin:0 0 6px;font-size:1rem;color:#2c1e4a;">🎯 Drag & Drop Field Editor</h3>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Drag fields to reposition. Double-click a field to edit font settings. Click "Save All Positions" when done.</p>

            <!-- Canvas container — holds the JPG + draggable overlays -->
            <div id="canvasContainer" style="position:relative;border:2px solid #ddd;border-radius:8px;overflow:hidden;background:#f0f0f0;display:inline-block;max-width:100%;">
                <img src="<?= $bgUrl ?>" alt="Template" id="templateImage" style="display:block;max-width:100%;height:auto;" onload="initDragDrop()">

                <?php foreach ($fields as $f):
                    $xPct = $tw > 0 ? ((float) $f['x_pos'] / $tw * 100) : 0;
                    $yPct = $th > 0 ? ((float) $f['y_pos'] / $th * 100) : 0;
                    $isQr = !empty($f['is_qrcode']);
                ?>
                <div class="field-overlay<?= $isQr ? ' field-qr' : '' ?>"
                     data-field-id="<?= (int) $f['id'] ?>"
                     data-x-pos="<?= (float) $f['x_pos'] ?>"
                     data-y-pos="<?= (float) $f['y_pos'] ?>"
                     data-font-size="<?= (int) $f['font_size'] ?>"
                     data-font-color="<?= htmlspecialchars($f['font_color'] ?? '#000000', ENT_QUOTES, 'UTF-8') ?>"
                     data-align="<?= htmlspecialchars($f['align'] ?? 'C', ENT_QUOTES, 'UTF-8') ?>"
                     data-qr-size="<?= (int) ($f['qr_size'] ?? 50) ?>"
                     data-is-qr="<?= $isQr ? 1 : 0 ?>"
                     style="position:absolute;left:<?= $xPct ?>%;top:<?= $yPct ?>%;transform:translate(-50%,-50%);cursor:move;user-select:none;
                            <?= $isQr ? 'width:60px;height:60px;' : 'min-width:60px;' ?>
                            background:<?= $isQr ? 'rgba(108,63,232,0.3)' : 'rgba(39,174,96,0.15)' ?>;
                            border:2px <?= $isQr ? 'solid #6c3fe8' : 'solid #27ae60' ?>;
                            border-radius:4px;padding:3px 8px;font-size:0.7rem;font-weight:600;
                            color:<?= $isQr ? '#6c3fe8' : '#27ae60' ?>;white-space:nowrap;z-index:10;">
                    <span class="field-label"><?= $isQr ? 'QR' : htmlspecialchars($f['field_key'], ENT_QUOTES, 'UTF-8') ?></span>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Save button -->
            <div style="margin-top:14px;display:flex;gap:10px;align-items:center;">
                <button type="button" id="saveAllBtn" style="padding:10px 24px;background:linear-gradient(135deg,#27ae60,#229954);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:0.88rem;cursor:pointer;">💾 Save All Positions</button>
                <span id="dirtyIndicator" style="font-size:0.82rem;color:#f39c12;display:none;">● Unsaved changes</span>
            </div>
        </div>

        <!-- RIGHT: Add Field + Field List + Editor -->
        <div style="display:flex;flex-direction:column;gap:14px;">

            <!-- Add Field -->
            <div class="admin-card" style="background:#fff;border-radius:12px;padding:18px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
                <h3 style="margin:0 0 12px;font-size:0.95rem;color:#2c1e4a;">+ Add Field</h3>
                <form method="POST" action="<?= $bp ?>/super-admin/certificate-templates/<?= (int) ($template['id'] ?? 0) ?>/fields">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">
                    <select name="field_key" required style="width:100%;padding:8px 10px;border:1px solid #ddd;border-radius:6px;font-size:0.82rem;margin-bottom:8px;">
                        <option value="">— Select Field —</option>
                        <optgroup label="Student Info">
                            <option value="student_name">Student Name</option>
                            <option value="father_name">Father Name</option>
                            <option value="mother_name">Mother Name</option>
                            <option value="roll_no">Roll No</option>
                            <option value="enrollment_no">Enrollment No</option>
                            <option value="dob">Date of Birth</option>
                            <option value="photo">Student Photo</option>
                        </optgroup>
                        <optgroup label="Course Info">
                            <option value="course">Course Name</option>
                            <option value="duration">Course Duration</option>
                            <option value="grade">Grade</option>
                            <option value="percentage">Percentage</option>
                            <option value="division">Division</option>
                        </optgroup>
                        <optgroup label="Dates">
                            <option value="admission_date">Admission Date</option>
                            <option value="completion_date">Completion Date</option>
                            <option value="issue_date">Issue Date</option>
                        </optgroup>
                        <optgroup label="Branch & Institute">
                            <option value="branch_name">Branch Name</option>
                            <option value="branch_code">Branch Code</option>
                            <option value="institute_name">Institute Name</option>
                            <option value="institute_logo">Institute Logo</option>
                            <option value="signature">Signature</option>
                            <option value="director_sign">Director Signature</option>
                            <option value="branch_sign">Branch Head Signature</option>
                        </optgroup>
                        <optgroup label="Document">
                            <option value="certificate_no">Certificate No</option>
                            <option value="qr_code">QR Code (verification)</option>
                        </optgroup>
                    </select>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;">
                        <input type="number" name="font_size" value="12" placeholder="Font" style="padding:6px 8px;border:1px solid #ddd;border-radius:4px;font-size:0.8rem;">
                        <input type="color" name="font_color" value="#000000" style="padding:4px;border:1px solid #ddd;border-radius:4px;height:32px;">
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;margin-top:6px;">
                        <select name="font_family" style="padding:6px;border:1px solid #ddd;border-radius:4px;font-size:0.78rem;">
                            <option value="Arial">Arial</option>
                            <option value="Times">Times</option>
                            <option value="Courier">Courier</option>
                        </select>
                        <select name="font_style" style="padding:6px;border:1px solid #ddd;border-radius:4px;font-size:0.78rem;">
                            <option value="">Regular</option>
                            <option value="B">Bold</option>
                            <option value="I">Italic</option>
                        </select>
                        <select name="align" style="padding:6px;border:1px solid #ddd;border-radius:4px;font-size:0.78rem;">
                            <option value="C">Center</option>
                            <option value="L">Left</option>
                            <option value="R">Right</option>
                        </select>
                    </div>
                    <label style="font-size:0.76rem;display:flex;align-items:center;gap:4px;margin-top:6px;">
                        <input type="checkbox" name="is_qrcode" value="1" style="width:14px;height:14px;"> This is a QR code
                    </label>
                    <button type="submit" style="width:100%;padding:8px;background:#27ae60;color:#fff;border:none;border-radius:6px;font-weight:600;font-size:0.82rem;cursor:pointer;margin-top:8px;">+ Add to Template</button>
                </form>
            </div>

            <!-- Field List (click to edit) -->
            <div class="admin-card" style="background:#fff;border-radius:12px;padding:18px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
                <h3 style="margin:0 0 12px;font-size:0.95rem;color:#2c1e4a;">Fields (<?= count($fields) ?>)</h3>
                <?php if (empty($fields)): ?>
                    <p style="text-align:center;color:#999;padding:12px 0;margin:0;font-size:0.82rem;">No fields yet. Add fields above.</p>
                <?php else: ?>
                    <div id="fieldList" style="display:flex;flex-direction:column;gap:6px;max-height:300px;overflow-y:auto;">
                        <?php foreach ($fields as $f): ?>
                        <div class="field-list-item" data-field-id="<?= (int) $f['id'] ?>" style="padding:8px 10px;background:#f9f9f9;border-radius:6px;border-left:3px solid <?= !empty($f['is_qrcode']) ? '#6c3fe8' : '#27ae60' ?>;cursor:pointer;" onclick="selectField(<?= (int) $f['id'] ?>)">
                            <div style="display:flex;justify-content:space-between;align-items:center;">
                                <span style="font-weight:600;color:#2c1e4a;font-size:0.82rem;"><?= htmlspecialchars($f['field_label'] ?? $f['field_key'], ENT_QUOTES, 'UTF-8') ?></span>
                                <form method="POST" action="<?= $bp ?>/super-admin/certificate-templates/<?= (int) ($template['id'] ?? 0) ?>/fields/<?= (int) $f['id'] ?>/delete" onsubmit="return confirm('Remove this field?');" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="submit" style="background:none;border:none;color:#e84118;cursor:pointer;font-size:0.8rem;padding:0;">✕</button>
                                </form>
                            </div>
                            <div style="font-size:0.7rem;color:#999;margin-top:2px;">
                                X: <?= (float) $f['x_pos'] ?> · Y: <?= (float) $f['y_pos'] ?> · <?= (int) $f['font_size'] ?>pt
                                <?php if (!empty($f['is_qrcode'])): ?> · QR <?= (int) $f['qr_size'] ?>pt<?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
.field-overlay:hover { box-shadow: 0 0 0 3px rgba(39,174,96,0.3); z-index:20; }
.field-overlay.dragging { opacity:0.7; z-index:30; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
.field-overlay.selected { border-color:#e84118 !important; box-shadow: 0 0 0 3px rgba(232,65,24,0.3); }
.field-list-item.selected { background:#fff3e0 !important; border-left-color:#e84118 !important; }
</style>

<script>
(function() {
    'use strict';

    var templateId = <?= (int) ($template['id'] ?? 0) ?>;
    var templateWidth = <?= $tw ?>;
    var templateHeight = <?= $th ?>;
    var csrfToken = <?= json_encode($csrfToken ?? '') ?>;
    var basePath = <?= json_encode($bp) ?>;
    var isDirty = false;
    var selectedFieldId = null;

    var canvasContainer = document.getElementById('canvasContainer');
    var templateImage = document.getElementById('templateImage');
    var saveBtn = document.getElementById('saveAllBtn');
    var dirtyIndicator = document.getElementById('dirtyIndicator');
    var saveStatus = document.getElementById('saveStatus');

    // ─── Initialize drag-and-drop ──────────────────────────────────────
    window.initDragDrop = function() {
        var overlays = document.querySelectorAll('.field-overlay');
        overlays.forEach(function(el) {
            makeDraggable(el);
        });
    };

    function makeDraggable(el) {
        var isDragging = false;
        var startX, startY, startLeft, startTop;

        el.addEventListener('mousedown', function(e) {
            if (e.button !== 0) return; // left click only
            e.preventDefault();
            isDragging = true;
            el.classList.add('dragging');
            selectField(parseInt(el.dataset.fieldId));

            var rect = canvasContainer.getBoundingClientRect();
            startX = e.clientX;
            startY = e.clientY;
            startLeft = el.offsetLeft;
            startTop = el.offsetTop;
        });

        document.addEventListener('mousemove', function(e) {
            if (!isDragging) return;
            e.preventDefault();

            var rect = canvasContainer.getBoundingClientRect();
            var deltaX = e.clientX - startX;
            var deltaY = e.clientY - startY;

            var newLeft = startLeft + deltaX;
            var newTop = startTop + deltaY;

            // Constrain within canvas
            newLeft = Math.max(0, Math.min(newLeft, rect.width));
            newTop = Math.max(0, Math.min(newTop, rect.height));

            el.style.left = (newLeft / rect.width * 100) + '%';
            el.style.top = (newTop / rect.height * 100) + '%';

            // Convert pixel position to point coordinates
            var xPoints = (newLeft / rect.width) * templateWidth;
            var yPoints = (newTop / rect.height) * templateHeight;

            el.dataset.xPos = xPoints.toFixed(2);
            el.dataset.yPos = yPoints.toFixed(2);

            // Update field list item display
            updateFieldListDisplay(parseInt(el.dataset.fieldId), xPoints, yPoints);

            markDirty();
        });

        document.addEventListener('mouseup', function() {
            if (isDragging) {
                isDragging = false;
                el.classList.remove('dragging');
            }
        });

        // Double-click to edit font settings
        el.addEventListener('dblclick', function(e) {
            e.preventDefault();
            e.stopPropagation();
            openFieldEditor(parseInt(el.dataset.fieldId));
        });
    }

    // ─── Select field (highlight in canvas + list) ─────────────────────
    window.selectField = function(fieldId) {
        selectedFieldId = fieldId;
        document.querySelectorAll('.field-overlay').forEach(function(el) {
            el.classList.toggle('selected', parseInt(el.dataset.fieldId) === fieldId);
        });
        document.querySelectorAll('.field-list-item').forEach(function(el) {
            el.classList.toggle('selected', parseInt(el.dataset.fieldId) === fieldId);
        });
    };

    function updateFieldListDisplay(fieldId, x, y) {
        var item = document.querySelector('.field-list-item[data-field-id="' + fieldId + '"]');
        if (item) {
            var coordsEl = item.querySelector('div:last-child');
            if (coordsEl) {
                var fontSize = document.querySelector('.field-overlay[data-field-id="' + fieldId + '"]')?.dataset.fontSize || 14;
                var isQr = document.querySelector('.field-overlay[data-field-id="' + fieldId + '"]')?.dataset.isQr === '1';
                coordsEl.innerHTML = 'X: ' + parseFloat(x).toFixed(1) + ' · Y: ' + parseFloat(y).toFixed(1) + ' · ' + fontSize + 'pt' + (isQr ? ' · QR' : '');
            }
        }
    }

    // ─── Mark dirty (unsaved changes) ──────────────────────────────────
    function markDirty() {
        isDirty = true;
        dirtyIndicator.style.display = 'inline';
        saveStatus.textContent = '● Unsaved changes';
        saveStatus.style.background = 'rgba(243,156,18,0.3)';
    }

    function markClean() {
        isDirty = false;
        dirtyIndicator.style.display = 'none';
        saveStatus.textContent = '✓ All changes saved';
        saveStatus.style.background = 'rgba(39,174,96,0.3)';
    }

    // ─── Save all positions via AJAX ───────────────────────────────────
    saveBtn.addEventListener('click', function() {
        var overlays = document.querySelectorAll('.field-overlay');
        var fieldsData = [];

        overlays.forEach(function(el) {
            fieldsData.push({
                id: parseInt(el.dataset.fieldId),
                x_pos: parseFloat(el.dataset.xPos),
                y_pos: parseFloat(el.dataset.yPos),
                font_size: parseInt(el.dataset.fontSize),
                font_color: el.dataset.fontColor,
                align: el.dataset.align,
                qr_size: parseInt(el.dataset.qrSize)
            });
        });

        if (fieldsData.length === 0) {
            alert('No fields to save.');
            return;
        }

        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';

        fetch(basePath + '/super-admin/certificate-templates/' + templateId + '/fields/bulk-update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({ fields: fieldsData, csrf_token: csrfToken })
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.success) {
                markClean();
                saveBtn.textContent = '✓ Saved!';
                setTimeout(function() { saveBtn.textContent = '💾 Save All Positions'; saveBtn.disabled = false; }, 2000);
            } else {
                alert('Save failed: ' + (data.error || 'Unknown error'));
                saveBtn.textContent = '💾 Save All Positions';
                saveBtn.disabled = false;
            }
        })
        .catch(function(err) {
            console.error('AJAX save failed:', err);
            saveBtn.textContent = '💾 Save All Positions';
            saveBtn.disabled = false;
            // Try to get more error details
            alert('Save failed: ' + err.message + '\n\nPlease check browser console (F12) for details. The positions are still tracked — try refreshing the page and repositioning.');
        });
    });

    // ─── Field editor (double-click popup) ─────────────────────────────
    function openFieldEditor(fieldId) {
        var overlay = document.querySelector('.field-overlay[data-field-id="' + fieldId + '"]');
        if (!overlay) return;

        var currentFontSize = parseInt(overlay.dataset.fontSize);
        var currentColor = overlay.dataset.fontColor;
        var currentAlign = overlay.dataset.align;

        var newFontSize = prompt('Font size (points):', currentFontSize);
        if (newFontSize === null) return;
        newFontSize = parseInt(newFontSize) || currentFontSize;

        var newColor = prompt('Font color (hex, e.g. #000000):', currentColor);
        if (newColor === null) return;
        if (!newColor.startsWith('#')) newColor = '#' + newColor;

        var newAlign = prompt('Align (L/C/R):', currentAlign);
        if (newAlign === null) return;
        newAlign = newAlign.toUpperCase();
        if (!['L','C','R'].includes(newAlign)) newAlign = 'C';

        // Update the overlay
        overlay.dataset.fontSize = newFontSize;
        overlay.dataset.fontColor = newColor;
        overlay.dataset.align = newAlign;

        // Visual feedback
        overlay.style.fontSize = Math.max(8, newFontSize * 0.5) + 'px';
        overlay.style.color = newColor;

        markDirty();
    }

    // Warn before leaving if unsaved
    window.addEventListener('beforeunload', function(e) {
        if (isDirty) {
            e.preventDefault();
            e.returnValue = 'You have unsaved field position changes. Leave anyway?';
        }
    });

    // Init on load
    if (templateImage.complete) {
        initDragDrop();
    }
})();
</script>
