<?php
/**
 * CAROUSEL JSON CONVERTER
 * 
 * This script converts base64 embedded images in carousel.json
 * to simple file path references.
 * 
 * It extracts base64 images and saves them as actual files,
 * then updates carousel.json with the file paths.
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/db_config.php';

$hostname = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
$is_local = (strpos($hostname, 'localhost') !== false || strpos($hostname, '127.0.0.1') !== false);
$is_cpanel = !$is_local;

echo "<h1>🎨 Carousel Image Converter</h1>";
echo "<p>Converts base64 embedded images to file references</p>";

$carouselFile = __DIR__ . '/data/carousel.json';
$uploadsDir = __DIR__ . '/uploads';

// Ensure uploads directory exists
if (!is_dir($uploadsDir)) {
    mkdir($uploadsDir, 0755, true);
    echo "<p>✅ Created uploads directory</p>";
}

if (!file_exists($carouselFile)) {
    echo "<p>❌ carousel.json not found</p>";
    exit;
}

// Read carousel.json
$carousel = json_decode(file_get_contents($carouselFile), true);
$updated = false;
$messages = [];

echo "<h2>Processing Categories:</h2>";
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Category</th><th>Action</th><th>Result</th></tr>";

if (isset($carousel['categories']) && is_array($carousel['categories'])) {
    foreach ($carousel['categories'] as $i => &$cat) {
        $catName = $cat['name'] ?? 'Unknown';
        $image = $cat['image'] ?? '';
        
        if (empty($image)) {
            echo "<tr><td>$catName</td><td>Skip</td><td>No image data</td></tr>";
            continue;
        }
        
        // Check if it's a base64 image
        if (strpos($image, 'data:image') === 0) {
            echo "<tr><td>$catName</td><td>Convert</td><td>";
            
            // Extract MIME type and data
            if (preg_match('/data:image\/(\w+);base64,(.+)/', $image, $matches)) {
                $mimeType = $matches[1];
                $base64Data = $matches[2];
                
                // Create sanitized filename
                $filename = strtolower(str_replace(' ', '_', $catName)) . '.' . $mimeType;
                $filepath = $uploadsDir . '/' . $filename;
                
                // Decode and save image
                $imageData = base64_decode($base64Data);
                if ($imageData && file_put_contents($filepath, $imageData)) {
                    // Update carousel entry with relative path
                    $cat['image'] = 'uploads/' . $filename;
                    $updated = true;
                    echo "✅ Saved as " . htmlspecialchars($filename) . "</td></tr>";
                } else {
                    echo "❌ Failed to save file</td></tr>";
                }
            } else {
                echo "❌ Invalid base64 format</td></tr>";
            }
        } else {
            // Already a path reference
            echo "<tr><td>$catName</td><td>Skip</td><td>Already a path: " . htmlspecialchars(substr($image, 0, 50)) . "...</td></tr>";
        }
    }
}
echo "</table>";

// Save updated carousel.json if changed
if ($updated) {
    echo "<h2>✅ Updates Found</h2>";
    if (file_put_contents($carouselFile, json_encode($carousel, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
        echo "<p>✅ carousel.json updated successfully!</p>";
        
        echo "<h3>Updated Content (First 500 chars):</h3>";
        echo "<pre style='background: #f0f0f0; padding: 10px; overflow-x: auto;'>";
        echo htmlspecialchars(substr(json_encode($carousel, JSON_PRETTY_PRINT), 0, 500));
        echo "...</pre>";
    } else {
        echo "<p>❌ Failed to save carousel.json - check file permissions</p>";
    }
} else {
    echo "<h2>ℹ️ No Changes Needed</h2>";
    echo "<p>All images are already using file path references (not base64).</p>";
}

echo "<h2>Next Steps:</h2>";
echo "<ol>";
echo "<li>Upload this updated files to cPanel via SFTP/File Manager</li>";
echo "<li>Ensure /uploads/ directory exists on cPanel</li>";
echo "<li>Set permissions: <code>chmod 755 /public_html/ecoms/uploads/</code></li>";
echo "<li>Test homepage to verify carousel images display</li>";
echo "</ol>";

echo "<p><a href='admin_manage_category_carousel.php'>← Back to Carousel Manager</a></p>";
?>
