<?php
session_start();
require_once 'config/database.php';
require_once 'includes/site_settings.php';

echo "<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Logo Gallery - Click to Activate</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        .logo-card {
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .logo-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        .logo-card.active {
            border: 3px solid #28a745 !important;
            background: #f0fff0 !important;
        }
        .logo-card:not(.active) {
            border: 1px solid #dee2e6;
        }
        .activate-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(40, 167, 69, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .logo-card:hover .activate-overlay {
            opacity: 1;
        }
        .activate-text {
            background: #28a745;
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: bold;
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            padding: 15px 25px;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            animation: slideIn 0.3s ease;
        }
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        .logo-preview {
            max-width: 100%;
            max-height: 150px;
            object-fit: contain;
            border-radius: 8px;
        }
        .status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            z-index: 2;
        }
        .active-badge {
            background: #28a745;
            color: white;
        }
        .inactive-badge {
            background: #6c757d;
            color: white;
        }
    </style>
</head>
<body>
    <div class='container mt-4'>
        <div class='row'>
            <div class='col-12'>
                <h1 class='text-center mb-4'>
                    <i class='fas fa-images me-2'></i>Logo Gallery
                </h1>
                <p class='text-center text-muted mb-4'>
                    Click on any logo to activate it for use in certificates
                </p>
            </div>
        </div>";

// Get current active logo
$session_logo = $_SESSION['custom_logo_path'] ?? null;

// Get all available logos (custom uploads + site logo)
$custom_logos = glob('uploads/logos/custom_logo_*.jpg');
$settings = get_all_settings($pdo);
$site_logo = $settings['logo_image'] ?? null;

echo "<div class='row mb-4'>
        <div class='col-12'>
            <div class='card bg-primary text-white'>
                <div class='card-body text-center'>
                    <h3><i class='fas fa-info-circle me-2'></i>Current Status</h3>";

if ($session_logo) {
    echo "<p class='mb-1'><strong>Active Logo:</strong> " . basename($session_logo) . "</p>";
    echo "<p class='mb-0'>This logo is currently being used in all certificates</p>";
} else {
    echo "<p class='mb-1'><strong>No Active Custom Logo</strong></p>";
    echo "<p class='mb-0'>Certificates are using the default site logo or fallback icon</p>";
}

echo "        </div>
            </div>
        </div>
    </div>";

echo "<div class='row'>";

// Display custom uploaded logos
if (!empty($custom_logos)) {
    echo "<div class='col-12 mb-4'>
            <h3><i class='fas fa-upload me-2'></i>Your Uploaded Logos</h3>
          </div>";
    
    foreach ($custom_logos as $logo_path) {
        $relative_path = str_replace(__DIR__ . '\\', '', $logo_path);
        $file_size = filesize($logo_path);
        $file_info = getimagesize($logo_path);
        $is_active = ($session_logo && strpos($session_logo, basename($logo_path)) !== false);
        $logo_name = basename($logo_path);
        
        echo "<div class='col-md-4 col-lg-3 mb-4'>
                <div class='card logo-card " . ($is_active ? 'active' : '') . "' 
                     onclick='activateLogo(\"$relative_path\", \"$logo_name\")'
                     data-logo-path='$relative_path'>
                    <div class='card-body text-center p-3'>";
        
        if ($is_active) {
            echo "<span class='status-badge active-badge'>ACTIVE</span>";
        } else {
            echo "<span class='status-badge inactive-badge'>INACTIVE</span>";
        }
        
        echo "          <img src='$relative_path' class='logo-preview mb-3' alt='Logo'>
                        <h6 class='card-title mb-2'>" . substr($logo_name, 0, 30) . (strlen($logo_name) > 30 ? '...' : '') . "</h6>
                        <div class='small text-muted mb-2'>
                            <div>" . round($file_size/1024, 1) . " KB</div>
                            <div>{$file_info[0]} × {$file_info[1]} px</div>
                        </div>";
        
        if (!$is_active) {
            echo "      <div class='activate-overlay'>
                            <div class='activate-text'>
                                <i class='fas fa-check-circle me-1'></i>ACTIVATE
                            </div>
                        </div>";
        }
        
        echo "      </div>
                </div>
            </div>";
    }
}

// Display site logo if it exists
if ($site_logo) {
    $full_site_path = __DIR__ . '/' . ltrim($site_logo, './');
    if (file_exists($full_site_path)) {
        $file_size = filesize($full_site_path);
        $file_info = getimagesize($full_site_path);
        $is_active = ($session_logo && strpos($session_logo, basename($site_logo)) !== false);
        
        echo "<div class='col-md-4 col-lg-3 mb-4'>
                <div class='card logo-card " . ($is_active ? 'active' : '') . "' 
                     onclick='activateLogo(\"$site_logo\", \"Site Logo\")'
                     data-logo-path='$site_logo'>
                    <div class='card-body text-center p-3'>";
        
        if ($is_active) {
            echo "<span class='status-badge active-badge'>ACTIVE</span>";
        }
        
        echo "          <img src='$site_logo' class='logo-preview mb-3' alt='Site Logo'>
                        <h6 class='card-title mb-2'>Site Logo</h6>
                        <div class='small text-muted mb-2'>
                            <div>" . round($file_size/1024, 1) . " KB</div>
                            <div>{$file_info[0]} × {$file_info[1]} px</div>
                        </div>";
        
        echo "      </div>
                </div>
            </div>";
    }
}

echo "</div>";

// Handle logo activation via AJAX
if (isset($_POST['activate_logo'])) {
    $logo_to_activate = $_POST['activate_logo'];
    $_SESSION['custom_logo_path'] = $logo_to_activate;
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Logo activated successfully!',
        'activated_logo' => basename($logo_to_activate)
    ]);
    exit;
}

echo "  </div>

    <!-- Notification Container -->
    <div id='notification-container'></div>

    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js'></script>
    
    <script>
        function activateLogo(logoPath, logoName) {
            // Send AJAX request to activate logo
            fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'activate_logo=' + encodeURIComponent(logoPath)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('✅ ' + data.message + ' Selected: ' + logoName, 'success');
                    // Reload page to show updated status
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showNotification('❌ Failed to activate logo', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('❌ Network error occurred', 'error');
            });
        }
        
        function showNotification(message, type) {
            const container = document.getElementById('notification-container');
            const notification = document.createElement('div');
            notification.className = 'notification';
            notification.style.background = type === 'success' ? '#28a745' : '#dc3545';
            notification.innerHTML = message;
            
            container.appendChild(notification);
            
            // Remove notification after 3 seconds
            setTimeout(() => {
                notification.remove();
            }, 3000);
        }
        
        // Add keyboard support (Enter key to activate focused logo)
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                const focusedCard = document.querySelector('.logo-card:focus');
                if (focusedCard) {
                    focusedCard.click();
                }
            }
        });
        
        // Add focus styles for accessibility
        document.querySelectorAll('.logo-card').forEach(card => {
            card.setAttribute('tabindex', '0');
            card.addEventListener('focus', function() {
                this.style.outline = '2px solid #007bff';
                this.style.outlineOffset = '2px';
            });
            card.addEventListener('blur', function() {
                this.style.outline = 'none';
            });
        });
    </script>
</body>
</html>";
?>