<!DOCTYPE html>
<html lang="hr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moj Panel - TapTap Card</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f5f7fa;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 { font-size: 28px; }
        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 20px;
            border: 2px solid white;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
        }
        .logout-btn:hover { background: rgba(255,255,255,0.3); }
        
        .container { max-width: 1200px; margin: 0 auto; }
        .card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .card h2 {
            font-size: 22px;
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .form-group {
            display: flex;
            flex-direction: column;
        }
        label {
            margin-bottom: 5px;
            color: #555;
            font-weight: 500;
            font-size: 14px;
        }
        input[type="text"],
        input[type="email"],
        input[type="tel"],
        input[type="color"],
        textarea,
        select {
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #667eea;
        }
        textarea { min-height: 100px; resize: vertical; }
        
        .btn {
            padding: 12px 24px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
        }
        .btn:hover { background: #5568d3; }
        .btn-success { background: #10b981; }
        .btn-success:hover { background: #059669; }
        .btn-danger { background: #ef4444; }
        .btn-danger:hover { background: #dc2626; }
        
        .link-item {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
        }
        .link-item select { flex: 0 0 150px; }
        .link-item input { flex: 1; }
        
        .module-box {
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
        }
        .module-box h3 { margin-bottom: 15px; color: #667eea; }
        .module-locked {
            opacity: 0.6;
            pointer-events: none;
            position: relative;
        }
        .module-locked::after {
            content: "🔒 Zaključao admin";
            position: absolute;
            top: 10px;
            right: 10px;
            background: #ef4444;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .preview-link {
            display: inline-block;
            margin-top: 10px;
            padding: 8px 16px;
            background: #3b82f6;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-size: 14px;
        }
        .preview-link:hover { background: #2563eb; }
        
        .image-upload-box {
            border: 2px dashed #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .image-upload-box:hover { border-color: #667eea; background: #f9fafb; }
        .image-preview {
            max-width: 200px;
            max-height: 200px;
            margin: 10px auto;
            border-radius: 8px;
        }
        
        .success-msg {
            background: #d1fae5;
            color: #065f46;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
            text-align: center;
        }
        .error-msg {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div>
                <h1>Moj TapTap Panel</h1>
                <p id="userWelcome"></p>
            </div>
            <button class="btn btn-primary" onclick="window.location.href='user-dashboard.php'" style="...">
    📊 Novi Dashboard
</button>
<button class="logout-btn" onclick="logout()">Odjava</button>
        </div>
        <button class="btn btn-primary" onclick="window.location.href='editor.php'">🎨 Live Editor</button>
        <div id="messages"></div>
        
        <!-- Osnovni podaci -->
        <div class="card">
            <h2>📋 Osnovni podaci</h2>
            <form id="basicForm">
                <div class="form-row">
                    <div class="form-group">
                        <label>Ime *</label>
                        <input type="text" id="ime" required>
                    </div>
                    <div class="form-group">
                        <label>Prezime *</label>
                        <input type="text" id="prezime" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label>Opis (titula, pozicija, firma...)</label>
                    <textarea id="opis"></textarea>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" id="email">
                    </div>
                    <div class="form-group">
                        <label>Telefon</label>
                        <input type="tel" id="telefon">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>WhatsApp</label>
                        <input type="tel" id="whatsapp">
                    </div>
                    <div class="form-group">
                        <label>Viber</label>
                        <input type="tel" id="viber">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Ulica i broj</label>
                        <input type="text" id="adresa">
                    </div>
                    <div class="form-group">
                        <label>Grad</label>
                        <input type="text" id="grad">
                    </div>
                    <div class="form-group">
                        <label>Država</label>
                        <input type="text" id="drzava">
                    </div>
                </div>
                
                <button type="submit" class="btn btn-success">💾 Spremi osnovne podatke</button>
            </form>
        </div>
        
        <!-- Dizajn -->
        <div class="card">
            <h2>🎨 Dizajn</h2>
            <div class="form-row">
                <div class="form-group">
                    <label>Glavna boja (accent)</label>
                    <input type="color" id="accent_color">
                </div>
            </div>
            
            <div class="form-group">
                <label>Pozadinska slika headera <small>(Preporučeno: 1200x400px)</small></label>
                <div class="image-upload-box" onclick="document.getElementById('bgUpload').click()">
                    <p>Klikni za upload</p>
                    <img id="bgPreview" class="image-preview" style="display:none;">
                </div>
                <input type="file" id="bgUpload" accept="image/*" style="display:none;">
            </div>
            
            <div class="form-group">
                <label>Profilna slika <small>(Preporučeno: 400x400px)</small></label>
                <div class="image-upload-box" onclick="document.getElementById('profileUpload').click()">
                    <p>Klikni za upload</p>
                    <img id="profilePreview" class="image-preview" style="display:none;">
                </div>
                <input type="file" id="profileUpload" accept="image/*" style="display:none;">
            </div>
            
            <button class="btn btn-success" onclick="saveDesign()">💾 Spremi dizajn</button>
        </div>
        
        <!-- Linkovi -->
        <div class="card">
            <h2>🔗 Društvene mreže i linkovi</h2>
            <div id="linksContainer"></div>
            <button class="btn" onclick="addLink()">➕ Dodaj link</button>
            <button class="btn btn-success" onclick="saveLinks()">💾 Spremi linkove</button>
        </div>
        
        <!-- Moduli -->
        <div class="card">
            <h2>⚙️ Moduli</h2>
            <div id="modulesContainer"></div>
        </div>
        
        <!-- Pregled -->
        <div class="card">
            <h2>👁️ Pregled</h2>
            <p>Pogledajte kako izgleda vaša kartica:</p>
            <a href="#" id="previewLink" target="_blank" class="preview-link">🔗 Otvori moju karticu</a>
        </div>
    </div>

    <script>
        let userData = null;
        let userLinks = [];
        let userModules = [];
        
        const linkTypes = {
            'instagram': 'Instagram',
            'facebook': 'Facebook',
            'linkedin': 'LinkedIn',
            'twitter': 'Twitter (X)',
            'tiktok': 'TikTok',
            'youtube': 'YouTube',
            'website': 'Website',
            'custom': 'Prilagođeni link'
        };
        
        // Provjera tokena
        async function checkAuth() {
            const token = localStorage.getItem('user_token');
            if (!token) {
                window.location.href = 'user-login.php';
                return;
            }
            
            try {
                const response = await fetch('/api.php/user/me', {
                    headers: { 'Authorization': 'Bearer ' + token }
                });
                
                if (!response.ok) throw new Error();
                
                userData = await response.json();
                loadUserData();
            } catch {
                localStorage.removeItem('user_token');
                window.location.href = 'user-login.php';
            }
        }
        
        function loadUserData() {
            document.getElementById('userWelcome').textContent = `Bok, ${userData.ime} ${userData.prezime}!`;
            
            // Osnovni podaci
            document.getElementById('ime').value = userData.ime || '';
            document.getElementById('prezime').value = userData.prezime || '';
            document.getElementById('opis').value = userData.opis || '';
            document.getElementById('email').value = userData.email || '';
            document.getElementById('telefon').value = userData.telefon || '';
            document.getElementById('whatsapp').value = userData.whatsapp || '';
            document.getElementById('viber').value = userData.viber || '';
            document.getElementById('adresa').value = userData.adresa || '';
            document.getElementById('grad').value = userData.grad || '';
            document.getElementById('drzava').value = userData.drzava || '';
            
            // Dizajn
            document.getElementById('accent_color').value = userData.accent_color || '#3b82f6';
            
            if (userData.background_image) {
                const img = document.getElementById('bgPreview');
                img.src = userData.background_image;
                img.style.display = 'block';
            }
            
            if (userData.slika) {
                const img = document.getElementById('profilePreview');
                img.src = userData.slika;
                img.style.display = 'block';
            }
            
            // Preview link
            document.getElementById('previewLink').href = `/${userData.slug}`;
            
            // Linkovi
            userLinks = userData.links || [];
            renderLinks();
            
            // Moduli
            userModules = userData.modules || [];
            renderModules();
        }
        
        function renderLinks() {
            const container = document.getElementById('linksContainer');
            container.innerHTML = '';
            
            userLinks.forEach((link, index) => {
                const div = document.createElement('div');
                div.className = 'link-item';
                div.innerHTML = `
                    <select data-index="${index}">
                        ${Object.entries(linkTypes).map(([key, label]) => 
                            `<option value="${key}" ${link.tip === key ? 'selected' : ''}>${label}</option>`
                        ).join('')}
                    </select>
                    <input type="url" placeholder="https://..." value="${link.url}" data-index="${index}">
                    <button class="btn btn-danger" onclick="removeLink(${index})">🗑️</button>
                `;
                container.appendChild(div);
            });
        }
        
        function addLink() {
            userLinks.push({ tip: 'website', url: '' });
            renderLinks();
        }
        
        function removeLink(index) {
            userLinks.splice(index, 1);
            renderLinks();
        }
        
        async function saveLinks() {
            const linkItems = document.querySelectorAll('.link-item');
            userLinks = Array.from(linkItems).map(item => ({
                tip: item.querySelector('select').value,
                url: item.querySelector('input').value
            })).filter(link => link.url);
            
            await saveData('/api.php/user/links', { links: userLinks });
        }
        
        function renderModules() {
            const container = document.getElementById('modulesContainer');
            container.innerHTML = '';
            
            const textBlock = userModules.find(m => m.modul_name === 'text_block');
            const workingHours = userModules.find(m => m.modul_name === 'working_hours');
            const mapa = userModules.find(m => m.modul_name === 'mapa');
            
            // Text block
            if (textBlock) {
                const div = document.createElement('div');
                div.className = 'module-box' + (textBlock.locked ? ' module-locked' : '');
                div.innerHTML = `
                    <h3>📝 Tekstualni blok</h3>
                    <textarea id="text_block_content" style="width:100%; min-height:120px;">${textBlock.config?.text || ''}</textarea>
                    <button class="btn btn-success" onclick="saveModule('text_block')">💾 Spremi</button>
                `;
                container.appendChild(div);
            }
            
            // Working hours
            if (workingHours) {
                const config = workingHours.config || {};
                const div = document.createElement('div');
                div.className = 'module-box' + (workingHours.locked ? ' module-locked' : '');
                div.innerHTML = `
                    <h3>🕐 Radno vrijeme</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Radnim danom</label>
                            <input type="text" id="weekday" value="${config.weekday || ''}" placeholder="08:00 - 16:00">
                        </div>
                        <div class="form-group">
                            <label>Subotom</label>
                            <input type="text" id="saturday" value="${config.saturday || ''}" placeholder="Ne radimo">
                        </div>
                        <div class="form-group">
                            <label>Nedjeljom</label>
                            <input type="text" id="sunday" value="${config.sunday || ''}" placeholder="Ne radimo">
                        </div>
                    </div>
                    <button class="btn btn-success" onclick="saveModule('working_hours')">💾 Spremi</button>
                `;
                container.appendChild(div);
            }
            
            // Mapa
            if (mapa) {
                const div = document.createElement('div');
                div.className = 'module-box' + (mapa.locked ? ' module-locked' : '');
                div.innerHTML = `
                    <h3>🗺️ Google Maps</h3>
                    <input type="text" id="mapa_link" value="${mapa.config?.link || ''}" 
                           placeholder="Naziv lokacije ili Google Maps link" style="width:100%; padding:12px;">
                    <button class="btn btn-success" onclick="saveModule('mapa')">💾 Spremi</button>
                `;
                container.appendChild(div);
            }
        }
        
        async function saveModule(moduleName) {
            let config = {};
            
            if (moduleName === 'text_block') {
                config = { text: document.getElementById('text_block_content').value };
            } else if (moduleName === 'working_hours') {
                config = {
                    type: 'weekday_weekend',
                    weekday: document.getElementById('weekday').value,
                    saturday: document.getElementById('saturday').value,
                    sunday: document.getElementById('sunday').value
                };
            } else if (moduleName === 'mapa') {
                config = { link: document.getElementById('mapa_link').value };
            }
            
            await saveData('/api.php/user/module', { module_name: moduleName, config });
        }
        
        // Upload slika
        document.getElementById('bgUpload').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(ev) {
                    const img = document.getElementById('bgPreview');
                    img.src = ev.target.result;
                    img.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });
        
        document.getElementById('profileUpload').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(ev) {
                    const img = document.getElementById('profilePreview');
                    img.src = ev.target.result;
                    img.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });
        
        async function saveDesign() {
            const formData = new FormData();
            formData.append('accent_color', document.getElementById('accent_color').value);
            
            const bgFile = document.getElementById('bgUpload').files[0];
            if (bgFile) formData.append('background_image', bgFile);
            
            const profileFile = document.getElementById('profileUpload').files[0];
            if (profileFile) formData.append('profile_image', profileFile);
            
            const token = localStorage.getItem('user_token');
            const response = await fetch('/api.php/user/design', {
                method: 'POST',
                headers: { 'Authorization': 'Bearer ' + token },
                body: formData
            });
            
            if (response.ok) {
                showMessage('Dizajn spremljen!', 'success');
            } else {
                showMessage('Greška pri spremanju', 'error');
            }
        }
        
        // Osnovni podaci
        document.getElementById('basicForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const data = {
                ime: document.getElementById('ime').value,
                prezime: document.getElementById('prezime').value,
                opis: document.getElementById('opis').value,
                email: document.getElementById('email').value,
                telefon: document.getElementById('telefon').value,
                whatsapp: document.getElementById('whatsapp').value,
                viber: document.getElementById('viber').value,
                adresa: document.getElementById('adresa').value,
                grad: document.getElementById('grad').value,
                drzava: document.getElementById('drzava').value
            };
            
            await saveData('/api.php/user/profile', data);
        });
        
        async function saveData(url, data) {
            const token = localStorage.getItem('user_token');
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    showMessage('Spremljeno!', 'success');
                } else {
                    showMessage('Greška pri spremanju', 'error');
                }
            } catch {
                showMessage('Greška pri povezivanju', 'error');
            }
        }
        
        function showMessage(text, type) {
            const div = document.getElementById('messages');
            div.innerHTML = `<div class="${type}-msg">${text}</div>`;
            setTimeout(() => div.innerHTML = '', 3000);
        }
        
        function logout() {
            localStorage.removeItem('user_token');
            window.location.href = 'user-login.php';
        }
        
        checkAuth();
    </script>
</body>
</html>
