<?php
if (!defined('INSTALLED')) require_once dirname(__DIR__) . '/config/config.php';
$adminTitle = 'PDF Design Studio';
include 'includes/header.php';

// Fetch current configuration if exists
$config = json_decode(setting('invoice_template_config', '{}'), true);

// Default layout if empty
if (empty($config)) {
    $config = [
        'blocks' => [
            'logo' => ['x' => 40, 'y' => 40, 'w' => 150, 'h' => 60, 'visible' => true],
            'header_text' => ['x' => 450, 'y' => 40, 'w' => 150, 'h' => 100, 'visible' => true, 'text' => 'INVOICE'],
            'client_box' => ['x' => 40, 'y' => 150, 'w' => 250, 'h' => 100, 'visible' => true],
            'invoice_meta' => ['x' => 350, 'y' => 150, 'w' => 200, 'h' => 100, 'visible' => true],
            'items_table' => ['x' => 40, 'y' => 300, 'w' => 520, 'h' => 400, 'visible' => true],
            'totals_box' => ['x' => 350, 'y' => 720, 'w' => 200, 'h' => 120, 'visible' => true],
            'footer_note' => ['x' => 40, 'y' => 850, 'w' => 520, 'h' => 60, 'visible' => true]
        ]
    ];
}
?>

<div class="p-6">
    <div class="flex items-center justify-between mb-8">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-tighter">PDF <span class="text-orange-500">Design Studio</span></h1>
            <p class="text-gray-500 text-xs font-bold uppercase tracking-widest mt-1">Drag, Drop & Resize your Invoice/Estimate Templates</p>
        </div>
        <div class="flex gap-3">
            <button onclick="saveTemplate()" class="bg-orange-600 text-white px-6 py-2.5 rounded-xl font-bold text-sm hover:bg-orange-700 transition-all flex items-center gap-2">
                <span class="text-lg">💾</span> Save Design
            </button>
            <button onclick="resetTemplate()" class="bg-navy-700 text-gray-400 px-6 py-2.5 rounded-xl font-bold text-sm hover:text-white transition-all">
                Reset Default
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        
        <!-- Sidebar Controls -->
        <div class="lg:col-span-1 space-y-6">
            <div class="bg-navy-800 border border-white/5 rounded-2xl p-6">
                <h3 class="text-xs font-black text-white uppercase tracking-widest mb-6 border-b border-white/5 pb-4">Studio Controls</h3>
                
                <div class="space-y-4">
                    <div class="p-4 bg-navy-900 rounded-xl border border-white/5">
                        <label class="block text-[10px] font-black text-gray-500 uppercase mb-2">Editor Snap-to-Grid</label>
                        <select id="grid-snap" class="w-full bg-navy-800 border-none rounded-lg text-sm text-white focus:ring-1 focus:ring-orange-500">
                            <option value="1">Off</option>
                            <option value="5">5px Snipping</option>
                            <option value="10" selected>10px Standard</option>
                            <option value="20">20px Loose</option>
                        </select>
                    </div>

                    <div class="p-4 bg-navy-900 rounded-xl border border-white/5">
                        <label class="block text-[10px] font-black text-gray-500 uppercase mb-2">Display Elements</label>
                        <div class="space-y-2" id="visibility-controls">
                            <!-- JS injected controls -->
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-orange-600/5 border border-orange-600/20 rounded-2xl p-6">
                <h4 class="text-[10px] font-black text-orange-500 uppercase tracking-widest mb-2 italic">Pro Tip</h4>
                <p class="text-[11px] text-gray-400 leading-relaxed">Blue handles resize blocks. Grey areas are for dragging. Double-click text to edit technical headers.</p>
            </div>
        </div>

        <!-- Canvas Area -->
        <div class="lg:col-span-3 flex justify-center bg-navy-900 rounded-3xl p-12 overflow-auto border border-white/5 shadow-inner">
            <div id="invoice-canvas" class="relative bg-white shadow-2xl overflow-hidden" style="width: 595px; height: 842px; min-width: 595px;">
                <!-- Grid Lines -->
                <div class="absolute inset-0 pointer-events-none opacity-[0.03]" style="background-image: radial-gradient(#000 0.5px, transparent 0.5px); background-size: 10px 10px;"></div>
                
                <!-- Draggable Blocks -->
                <div id="logo" class="draggable resizable absolute bg-blue-50/50 border border-dashed border-blue-400 flex items-center justify-center overflow-hidden" data-id="logo">
                   <img src="../uploads/<?= e(setting('logo')) ?>" class="max-w-full max-h-full object-contain pointer-events-none">
                   <div class="resize-handle"></div>
                </div>

                <div id="header_text" class="draggable resizable absolute bg-gray-100/50 border border-dashed border-gray-400 p-2" data-id="header_text">
                    <div class="text-4xl font-black text-navy-900 uppercase">INVOICE</div>
                    <div class="resize-handle"></div>
                </div>

                <div id="client_box" class="draggable resizable absolute bg-gray-50 border border-dashed border-gray-300 p-4" data-id="client_box">
                    <div class="text-[10px] text-gray-500 font-bold uppercase mb-2">Bill To:</div>
                    <div class="font-bold text-navy-900">M/S GLOBAL ENERGY CORP</div>
                    <div class="text-xs text-gray-600 mt-1">Plot 45, Industrial Zone B, Karachi</div>
                    <div class="resize-handle"></div>
                </div>

                <div id="invoice_meta" class="draggable resizable absolute bg-gray-50 border border-dashed border-gray-300 p-4" data-id="invoice_meta">
                    <div class="grid grid-cols-2 gap-2 text-[10px] text-navy-900">
                        <span class="font-bold">INV #</span> <span>INV-2024-001</span>
                        <span class="font-bold">Date</span> <span>12-Apr-2026</span>
                    </div>
                    <div class="resize-handle"></div>
                </div>

                <div id="items_table" class="draggable resizable absolute bg-white border border-dashed border-gray-300" data-id="items_table">
                    <table class="w-full text-left text-[10px]">
                        <thead class="bg-navy-900 text-white font-black uppercase">
                            <tr>
                                <th class="p-2 border border-white/5">Item Description</th>
                                <th class="p-2 border border-white/5">Qty</th>
                                <th class="p-2 border border-white/5">Price</th>
                                <th class="p-2 border border-white/5">Total</th>
                            </tr>
                        </thead>
                        <tbody class="text-navy-900">
                            <tr>
                                <td class="p-2 border border-gray-200">API 6A Wellhead Gate Valve 3"</td>
                                <td class="p-2 border border-gray-200">2</td>
                                <td class="p-2 border border-gray-200">55,000</td>
                                <td class="p-2 border border-gray-200">110,000</td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="resize-handle"></div>
                </div>

                <div id="totals_box" class="draggable resizable absolute bg-navy-900 border border-dashed border-orange-500 p-4 text-white" data-id="totals_box">
                    <div class="space-y-1 text-xs">
                        <div class="flex justify-between opacity-60"><span>Subtotal:</span> <span>110,000</span></div>
                        <div class="flex justify-between font-black text-orange-500 border-t border-white/10 pt-2"><span>Total:</span> <span>PKR 110,000</span></div>
                    </div>
                    <div class="resize-handle"></div>
                </div>

                <div id="footer_note" class="draggable resizable absolute bg-gray-50 border border-dashed border-gray-300 p-2 text-[9px] text-gray-500 italic" data-id="footer_note">
                    Standard terms apply. Mill test reports (MTR) provided upon request. Precision engineering by Rig N Dig.
                    <div class="resize-handle"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .draggable { cursor: move; user-select: none; }
    .resizable { border-width: 1px !important; }
    .resize-handle {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 10px;
        height: 10px;
        background: #3b82f6;
        cursor: se-resize;
        border-radius: 2px 0 0 0;
    }
    .dragging { opacity: 0.5; cursor: grabbing !important; }
    .active-block { border-style: solid !important; ring: 2px; }
</style>

<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<script>
    let templateConfig = <?= json_encode($config) ?>;

    // Initialize Layout from config
    function initLayout() {
        Object.keys(templateConfig.blocks).forEach(id => {
            const block = document.getElementById(id);
            if (!block) return;
            
            const data = templateConfig.blocks[id];
            block.style.left = data.x + 'px';
            block.style.top = data.y + 'px';
            block.style.width = data.w + 'px';
            block.style.height = data.h + 'px';
            block.style.display = data.visible ? 'block' : 'none';
            
            // Toggle side control
            createControl(id, data.visible);
        });
    }

    function createControl(id, visible) {
        const container = document.getElementById('visibility-controls');
        const div = document.createElement('div');
        div.className = "flex items-center justify-between";
        div.innerHTML = `
            <span class="text-[10px] text-gray-400 uppercase font-black">${id.replace('_', ' ')}</span>
            <input type="checkbox" ${visible ? 'checked' : ''} onchange="toggleBlock('${id}', this.checked)" class="rounded bg-navy-800 border-navy-600 text-orange-600 focus:ring-0">
        `;
        container.appendChild(div);
    }

    function toggleBlock(id, visible) {
        const el = document.getElementById(id);
        if (el) el.style.display = visible ? 'block' : 'none';
        templateConfig.blocks[id].visible = visible;
    }

    interact('.draggable')
      .draggable({
        inertia: true,
        modifiers: [
          interact.modifiers.restrictRect({
            restriction: 'parent',
            endOnly: true
          }),
          interact.modifiers.snap({
            targets: [
                interact.snappers.grid({ x: 10, y: 10 })
            ],
            range: Infinity,
            relativePoints: [ { x: 0, y: 0 } ]
          })
        ],
        onmove: dragMoveListener,
        onend: function (event) {
            updateConfig(event.target);
        }
      })
      .resizable({
        edges: { left: false, right: true, bottom: true, top: false },
        listeners: {
          move (event) {
            var target = event.target
            var x = (parseFloat(target.getAttribute('data-x')) || 0)
            var y = (parseFloat(target.getAttribute('data-y')) || 0)

            target.style.width = event.rect.width + 'px'
            target.style.height = event.rect.height + 'px'
            
            updateConfig(target);
          }
        }
      });

    function dragMoveListener (event) {
        var target = event.target
        var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
        var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy

        target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'

        target.setAttribute('data-x', x)
        target.setAttribute('data-y', y)
    }

    function updateConfig(el) {
        const id = el.getAttribute('data-id');
        const rect = el.getBoundingClientRect();
        const canvasRect = document.getElementById('invoice-canvas').getBoundingClientRect();
        
        const x = el.offsetLeft + (parseFloat(el.getAttribute('data-x')) || 0);
        const y = el.offsetTop + (parseFloat(el.getAttribute('data-y')) || 0);
        
        templateConfig.blocks[id].x = x;
        templateConfig.blocks[id].y = y;
        templateConfig.blocks[id].w = el.offsetWidth;
        templateConfig.blocks[id].h = el.offsetHeight;
    }

    async function saveTemplate() {
        // Send via AJAX to a handler
        const formData = new FormData();
        formData.append('config', JSON.stringify(templateConfig));
        
        try {
            const res = await fetch('api/save_template.php', {
                method: 'POST',
                body: formData
            });
            const data = await res.json();
            if (data.success) {
                alert('Design saved successfully! Your invoices will now use this layout.');
            }
        } catch (e) {
            console.error(e);
            alert('Error saving template. Ensure api/save_template.php exists.');
        }
    }

    initLayout();
</script>

<?php include 'includes/footer.php'; ?>
