<?php
/**
 * Badge Generator & Designer
 * Interactive badge design and preview tool
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login
requirePermission('delegates', 'view');

$currentPage = 'badges';

try {
    $pdo = getDBConnection();
    
    // Get badge settings
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM badge_settings");
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Get a sample delegate for preview
    $sample_delegate_query = "
        SELECT d.*, r.registration_number, r.university_name, r.contact_department, r.country
        FROM delegates d
        JOIN registrations r ON d.registration_id = r.id
        ORDER BY r.created_at DESC
        LIMIT 1
    ";
    $sample_delegate = $pdo->query($sample_delegate_query)->fetch(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Badge Designer - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .designer-layout {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 2rem;
            margin-top: 2rem;
        }
        
        .preview-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 2rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 600px;
        }
        
        .controls-section {
            background: white;
            border-radius: 12px;
            box-shadow: var(--shadow);
            padding: 1.5rem;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .controls-section h3 {
            margin: 0 0 1rem 0;
            color: #2c3e50;
            font-size: 1.1rem;
            font-weight: 600;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e9ecef;
        }
        
        .control-group {
            margin-bottom: 1.5rem;
        }
        
        .control-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #374151;
            font-size: 13px;
        }
        
        .control-group select {
            width: 100%;
            padding: 0.6rem;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .control-group select:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .badge-preview-wrapper {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
        }
        
        .preview-actions {
            margin-top: 1.5rem;
            display: flex;
            gap: 1rem;
            justify-content: center;
        }
        
        .info-card {
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .info-card h4 {
            margin: 0 0 0.5rem 0;
            color: #1e40af;
            font-size: 14px;
            font-weight: 600;
        }
        
        .info-card p {
            margin: 0;
            color: #1e40af;
            font-size: 13px;
            line-height: 1.5;
        }
        
        .delegate-info {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .delegate-info .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e5e7eb;
            font-size: 13px;
        }
        
        .delegate-info .info-row:last-child {
            border-bottom: none;
        }
        
        .delegate-info .info-label {
            font-weight: 600;
            color: #6b7280;
        }
        
        .delegate-info .info-value {
            color: #1f2937;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header" style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1>🎨 Badge Designer</h1>
                <p>Preview and customize event badge design</p>
            </div>
            <div style="display: flex; gap: 0.75rem;">
                <a href="badge-settings.php" class="btn btn-secondary">
                    ⚙️ Settings
                </a>
                <a href="badges.php" class="btn btn-primary">
                    ← Back to Badges
                </a>
            </div>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php else: ?>

        <div class="designer-layout">
            <!-- Preview Section -->
            <div class="preview-section">
                <h2 style="margin-bottom: 1.5rem; color: #1f2937; font-size: 1.5rem; font-weight: 700;">
                    Live Preview
                </h2>
                
                <div class="badge-preview-wrapper">
                    <div id="badgePreview">
                        <?php if ($sample_delegate): ?>
                            <div style="text-align: center; padding: 2rem; color: #6b7280;">
                                Loading preview...
                            </div>
                        <?php else: ?>
                            <div style="text-align: center; padding: 2rem; color: #6b7280;">
                                <p>No delegates available for preview.</p>
                                <p>Please add delegates first.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($sample_delegate): ?>
                <div class="preview-actions">
                    <button onclick="refreshPreview()" class="btn btn-primary">
                        🔄 Refresh Preview
                    </button>
                    <button onclick="printSampleBadge()" class="btn btn-success">
                        🖨️ Print Sample
                    </button>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Controls Section -->
            <div class="controls-section">
                <h3>🎯 Preview Controls</h3>
                
                <div class="info-card">
                    <h4>💡 Quick Tip</h4>
                    <p>Select different delegates to preview how badges will look with various name lengths and university names.</p>
                </div>
                
                <?php if ($sample_delegate): ?>
                <div class="control-group">
                    <label for="delegate_selector">Select Delegate</label>
                    <select id="delegate_selector" onchange="changeDelegate(this.value)">
                        <option value="">Loading delegates...</option>
                    </select>
                </div>
                
                <div class="delegate-info" id="delegateInfo">
                    <div class="info-row">
                        <span class="info-label">Name:</span>
                        <span class="info-value"><?php echo htmlspecialchars($sample_delegate['full_name']); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Badge Name:</span>
                        <span class="info-value"><?php echo htmlspecialchars($sample_delegate['badge_name']); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Designation:</span>
                        <span class="info-value"><?php echo htmlspecialchars($sample_delegate['designation']); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">University:</span>
                        <span class="info-value"><?php echo htmlspecialchars($sample_delegate['university_name']); ?></span>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="info-card" style="background: #fef3c7; border-color: #fde047;">
                    <h4 style="color: #854d0e;">⚙️ Badge Configuration</h4>
                    <p style="color: #854d0e;">
                        To customize badge colors, logos, and layout, go to 
                        <strong><a href="badge-settings.php" style="color: #854d0e; text-decoration: underline;">Badge Settings</a></strong>
                    </p>
                </div>
                
                <div style="margin-top: 2rem; padding-top: 2rem; border-top: 2px solid #e9ecef;">
                    <h4 style="margin: 0 0 1rem 0; color: #374151; font-size: 14px; font-weight: 600;">
                        Badge Specifications
                    </h4>
                    <div style="font-size: 13px; color: #6b7280; line-height: 1.8;">
                        <p><strong>Dimensions:</strong> <?php echo htmlspecialchars($settings['badge_width'] ?? '340'); ?>px × <?php echo htmlspecialchars($settings['badge_height'] ?? '500'); ?>px</p>
                        <p><strong>Format:</strong> HTML/CSS with print support</p>
                        <p><strong>QR Code:</strong> <?php echo ($settings['enable_qr_code'] ?? 'true') === 'true' ? 'Enabled' : 'Disabled'; ?></p>
                        <p><strong>Event:</strong> <?php echo htmlspecialchars($settings['event_name'] ?? 'Applied HE>X CHANGE'); ?></p>
                        <p><strong>Date:</strong> <?php echo htmlspecialchars($settings['event_dates'] ?? '27-28 FEB 2025'); ?></p>
                    </div>
                </div>
            </div>
        </div>

        <?php endif; ?>
    </div>

    <script>
        let currentDelegateId = <?php echo $sample_delegate ? $sample_delegate['id'] : 'null'; ?>;
        
        // Load badge preview on page load
        document.addEventListener('DOMContentLoaded', function() {
            if (currentDelegateId) {
                loadBadgePreview(currentDelegateId);
                loadDelegatesList();
            }
        });
        
        function loadBadgePreview(delegateId) {
            const previewEl = document.getElementById('badgePreview');
            previewEl.innerHTML = '<div style="text-align: center; padding: 2rem; color: #6b7280;">Loading preview...</div>';
            
            fetch(`badge_api.php?action=preview&delegate_id=${delegateId}`)
                .then(response => response.text())
                .then(html => {
                    previewEl.innerHTML = html;
                })
                .catch(error => {
                    previewEl.innerHTML = '<div style="text-align: center; padding: 2rem; color: #ef4444;">Error loading preview: ' + error.message + '</div>';
                });
        }
        
        function loadDelegatesList() {
            fetch('get_delegates_list.php')
                .then(response => response.json())
                .then(delegates => {
                    const selector = document.getElementById('delegate_selector');
                    selector.innerHTML = delegates.map(d => 
                        `<option value="${d.id}" ${d.id == currentDelegateId ? 'selected' : ''}>
                            ${d.registration_number} - ${d.badge_name}
                        </option>`
                    ).join('');
                })
                .catch(error => {
                    console.error('Error loading delegates list:', error);
                });
        }
        
        function changeDelegate(delegateId) {
            if (!delegateId) return;
            
            currentDelegateId = delegateId;
            loadBadgePreview(delegateId);
            
            // Update delegate info
            fetch(`get_delegate_info.php?id=${delegateId}`)
                .then(response => response.json())
                .then(delegate => {
                    document.getElementById('delegateInfo').innerHTML = `
                        <div class="info-row">
                            <span class="info-label">Name:</span>
                            <span class="info-value">${delegate.full_name}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Badge Name:</span>
                            <span class="info-value">${delegate.badge_name}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Designation:</span>
                            <span class="info-value">${delegate.designation}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">University:</span>
                            <span class="info-value">${delegate.university_name}</span>
                        </div>
                    `;
                })
                .catch(error => {
                    console.error('Error loading delegate info:', error);
                });
        }
        
        function refreshPreview() {
            if (currentDelegateId) {
                loadBadgePreview(currentDelegateId);
            }
        }
        
        function printSampleBadge() {
            if (currentDelegateId) {
                window.open(`badge_api.php?action=print&delegate_id=${currentDelegateId}`, '_blank');
            }
        }
    </script>

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

