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

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

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

// Handle different AJAX requests
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;
}

// Handle logo upload
if (isset($_FILES['custom_logo']) && $_FILES['custom_logo']['error'] == 0) {
    $upload_dir = 'uploads/logos/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $file_extension = strtolower(pathinfo($_FILES['custom_logo']['name'], PATHINFO_EXTENSION));
    
    if (in_array($file_extension, $allowed_extensions)) {
        $new_filename = 'custom_logo_' . time() . '_' . uniqid() . '.' . $file_extension;
        $upload_path = $upload_dir . $new_filename;
        
        if (move_uploaded_file($_FILES['custom_logo']['tmp_name'], $upload_path)) {
            // Set as active logo
            $_SESSION['custom_logo_path'] = $upload_path;
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'message' => 'Logo uploaded and activated successfully!',
                'logo_path' => $upload_path
            ]);
            exit;
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Failed to upload logo file'
    ]);
    exit;
}

// Handle logo display toggle
if (isset($_POST['show_logo'])) {
    // This would typically update database settings
    // For session-based implementation, we'll handle it in the main certificate file
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Logo display setting updated'
    ]);
    exit;
}

// Handle clear custom logo
if (isset($_POST['clear_custom_logo'])) {
    unset($_SESSION['custom_logo_path']);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Custom logo cleared successfully'
    ]);
    exit;
}

// If this is an AJAX request for logo gallery content
if (isset($_GET['gallery'])) {
    echo "<div class='col-12 mb-3'>
            <h5 class='text-center'><i class='fas fa-mouse-pointer me-2'></i>Click any logo to use it in certificates</h5>
          </div>";
    
    // Display custom uploaded logos
    if (!empty($custom_logos)) {
        echo "<div class='col-12 mb-3'>
                <h6><i class='fas fa-upload me-1'></i>Your Custom Logos</h6>
              </div>";
            
        foreach ($custom_logos as $logo_path) {
            // Handle both Windows and Unix path separators
            $relative_path = str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $logo_path);
            $relative_path = str_replace('\\', '/', $relative_path); // Convert to forward slashes
                
            if (file_exists($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-3'>";
                echo "  <div class='card logo-thumbnail " . ($is_active ? 'active' : '') . "' 
                           onclick=\"selectLogo('" . addslashes($relative_path) . "', '" . addslashes($logo_name) . "')\"
                           style='height: 100%; cursor: pointer;'>";
                echo "      <div class='card-body text-center p-2'>";
                    
                if ($is_active) {
                    echo "<span class='badge bg-success position-absolute' style='top: 5px; right: 5px;'>ACTIVE</span>";
                }
                    
                echo "          <img src='$relative_path' class='img-fluid mb-2' style='max-height: 80px; object-fit: contain;' alt='Logo'>";
                echo "          <div class='small'>";
                echo "              <div class='fw-bold'>" . substr($logo_name, 0, 20) . (strlen($logo_name) > 20 ? '...' : '') . "</div>";
                echo "              <div class='text-muted'>" . round($file_size/1024, 1) . " KB</div>";
                echo "              <div class='text-muted'>{$file_info[0]}×{$file_info[1]}px</div>";
                echo "          </div>";
                echo "      </div>";
                echo "  </div>";
                echo "</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-3'>";
            echo "  <div class='card logo-thumbnail " . ($is_active ? 'active' : '') . "' 
                       onclick='selectLogo(\"$site_logo\", \"Site Logo\")'
                       style='height: 100%;'>";
            echo "      <div class='card-body text-center p-2'>";
            
            if ($is_active) {
                echo "<span class='badge bg-success position-absolute' style='top: 5px; right: 5px;'>ACTIVE</span>";
            }
            
            echo "          <img src='$site_logo' class='img-fluid mb-2' style='max-height: 80px; object-fit: contain;' alt='Site Logo'>";
            echo "          <div class='small'>";
            echo "              <div class='fw-bold'>Site Logo</div>";
            echo "              <div class='text-muted'>" . round($file_size/1024, 1) . " KB</div>";
            echo "              <div class='text-muted'>{$file_info[0]}×{$file_info[1]}px</div>";
            echo "          </div>";
            echo "      </div>";
            echo "  </div>";
            echo "</div>";
        }
    }

    // If no logos available
    if (empty($custom_logos) && !$site_logo) {
        echo "<div class='col-12 text-center py-5'>";
        echo "  <i class='fas fa-image fa-3x text-muted mb-3'></i>";
        echo "  <h5 class='text-muted'>No logos available</h5>";
        echo "  <p class='text-muted'>Upload a logo first to use this feature</p>";
        echo "  <button class='btn btn-primary' onclick='uploadNewLogo()'>";
        echo "      <i class='fas fa-upload me-1'></i>Upload Logo";
        echo "  </button>";
        echo "</div>";
    }
    
    exit;
}

// Main page content (if not AJAX request)
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Logo Selection</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container py-4">
        <div class="row">
            <?php include __FILE__ . '?gallery=1'; ?>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function selectLogo(logoPath, logoName) {
            // This would typically send an AJAX request
            // For demo purposes, we'll just show an alert
            alert('Selected: ' + logoName + '\nPath: ' + logoPath);
        }
        
        function uploadNewLogo() {
            alert('Redirect to upload page');
        }
    </script>
</body>
</html>