<?php
/**
 * MASTER IMAGE SYSTEM FIX
 * 
 * This script automatically:
 * 1. Scans database for image references
 * 2. Fixes paths that won't work on cPanel
 * 3. Normalizes all image paths to work on both localhost AND cPanel
 * 4. Provides detailed report of what was fixed
 */

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>🎨 Master Image System Fix</h1>";
echo "<p><strong>Environment:</strong> " . ($is_local ? "LOCALHOST" : "CPANEL") . "</p>";
echo "<hr>";

$stats = [
    'products_scanned' => 0,
    'products_fixed' => 0,
    'blogs_scanned' => 0,
    'blogs_fixed' => 0,
    'carousel_fixed' => false,
    'errors' => []
];

// ========================================
// PART 1: Fix Product Images
// ========================================
echo "<h2>📦 Fixing Product Images</h2>";

try {
    // Check if products table exists
    $tableCheck = $conn->query("SELECT * FROM information_schema.tables WHERE table_schema='{$DB_NAME}' AND table_name='products'");
    
    if ($tableCheck && $tableCheck->num_rows > 0) {
        $result = $conn->query("SELECT id, image FROM products LIMIT 1000");
        
        if ($result) {
            $stats['products_scanned'] = $result->num_rows;
            
            while ($product = $result->fetch_assoc()) {
                $originalImage = $product['image'] ?? '';
                $fixedImage = normalizeProductImage($originalImage);
                
                if ($fixedImage !== $originalImage && !empty($fixedImage)) {
                    // Update the product
                    $stmt = $conn->prepare("UPDATE products SET image = ? WHERE id = ?");
                    $stmt->bind_param("si", $fixedImage, $product['id']);
                    
                    if ($stmt->execute()) {
                        $stats['products_fixed']++;
                        echo "✅ Product {$product['id']}: {$originalImage} → {$fixedImage}<br>";
                    } else {
                        $stats['errors'][] = "Failed to update product {$product['id']}";
                    }
                    $stmt->close();
                }
            }
        }
    } else {
        echo "<p>ℹ️ Products table not found in database</p>";
        $stats['products_scanned'] = 0;
    }
} catch (Exception $e) {
    $stats['errors'][] = "Products error: " . $e->getMessage();
}

echo "<p>Fixed {$stats['products_fixed']} out of {$stats['products_scanned']} products</p>";

// ========================================
// PART 2: Fix Blog Featured Images
// ========================================
echo "<h2>📝 Fixing Blog Featured Images</h2>";

try {
    // Check if blogs table exists
    $tableCheck = $conn->query("SELECT * FROM information_schema.tables WHERE table_schema='{$DB_NAME}' AND table_name='blogs'");
    
    if ($tableCheck && $tableCheck->num_rows > 0) {
        $result = $conn->query("SELECT id, featured_image FROM blogs LIMIT 1000");
        
        if ($result) {
            $stats['blogs_scanned'] = $result->num_rows;
            
            while ($blog = $result->fetch_assoc()) {
                $originalImage = $blog['featured_image'] ?? '';
                $fixedImage = normalizeProductImage($originalImage);
                
                if ($fixedImage !== $originalImage && !empty($fixedImage)) {
                    // Update the blog
                    $stmt = $conn->prepare("UPDATE blogs SET featured_image = ? WHERE id = ?");
                    $stmt->bind_param("si", $fixedImage, $blog['id']);
                    
                    if ($stmt->execute()) {
                        $stats['blogs_fixed']++;
                        echo "✅ Blog {$blog['id']}: featured image fixed<br>";
                    } else {
                        $stats['errors'][] = "Failed to update blog {$blog['id']}";
                    }
                    $stmt->close();
                }
            }
        }
    } else {
        echo "<p>ℹ️ Blogs table not found in database</p>";
        $stats['blogs_scanned'] = 0;
    }
} catch (Exception $e) {
    $stats['errors'][] = "Blogs error: " . $e->getMessage();
}

echo "<p>Fixed {$stats['blogs_fixed']} out of {$stats['blogs_scanned']} blogs</p>";

// ========================================
// PART 3: Fix Carousel Images
// ========================================
echo "<h2>🎠 Fixing Carousel Images</h2>";

$carouselFile = __DIR__ . '/data/carousel.json';
if (file_exists($carouselFile)) {
    $carousel = json_decode(file_get_contents($carouselFile), true);
    $updated = false;
    
    if (isset($carousel['categories']) && is_array($carousel['categories'])) {
        foreach ($carousel['categories'] as &$cat) {
            $originalImage = $cat['image'] ?? '';
            $fixedImage = normalizeProductImage($originalImage);
            
            if ($fixedImage !== $originalImage) {
                $cat['image'] = $fixedImage;
                $updated = true;
                echo "✅ Category '{$cat['name']}': image path fixed<br>";
            }
        }
        unset($cat);
        
        if ($updated) {
            if (file_put_contents($carouselFile, json_encode($carousel, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
                $stats['carousel_fixed'] = true;
                echo "<p>✅ carousel.json updated successfully</p>";
            } else {
                $stats['errors'][] = "Failed to save carousel.json";
            }
        }
    }
}

// ========================================
// PART 4: Ensure Uploads Directory
// ========================================
echo "<h2>📁 Checking Upload Directory</h2>";

$uploadsDir = __DIR__ . '/uploads';
if (!is_dir($uploadsDir)) {
    if (@mkdir($uploadsDir, 0755, true)) {
        echo "✅ Created /uploads directory<br>";
    } else {
        echo "❌ Failed to create /uploads directory<br>";
        $stats['errors'][] = "Cannot create uploads directory";
    }
}

if (is_dir($uploadsDir)) {
    echo "✅ /uploads directory exists<br>";
    if (is_writable($uploadsDir)) {
        echo "✅ /uploads directory is writable<br>";
    } else {
        echo "⚠️  /uploads directory exists but is NOT writable<br>";
        $stats['errors'][] = "Uploads directory not writable - check permissions!";
    }
}

// ========================================
// SUMMARY
// ========================================
echo "<h2>📊 Summary</h2>";
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Category</th><th>Action</th><th>Result</th></tr>";
echo "<tr><td>Products</td><td>Fixed</td><td>" . $stats['products_fixed'] . " / " . $stats['products_scanned'] . "</td></tr>";
echo "<tr><td>Blogs</td><td>Fixed</td><td>" . $stats['blogs_fixed'] . " / " . $stats['blogs_scanned'] . "</td></tr>";
echo "<tr><td>Carousel</td><td>Fixed</td><td>" . ($stats['carousel_fixed'] ? 'Yes' : 'No') . "</td></tr>";
echo "</table>";

if (count($stats['errors']) > 0) {
    echo "<h3>⚠️ Warnings/Errors:</h3>";
    foreach ($stats['errors'] as $error) {
        echo "• " . htmlspecialchars($error) . "<br>";
    }
}

echo "<h2>✅ Next Steps</h2>";
echo "<ol>";
echo "<li>This fixed images in the database</li>";
echo "<li>Upload /uploads/ folder to cPanel if it has files</li>";
echo "<li>Upload all images from /pics_ecom/ to cPanel /pics_ecom/</li>";
echo "<li>Test homepage - all images should display on cPanel now</li>";
echo "</ol>";

echo "<p><a href='index.php'>← Back to Homepage</a></p>";

/**
 * Normalize product/blog image paths
 * 
 * Fixes common issues:
 * - Removes localhost URLs
 * - Normalizes path separators
 * - Ensures relative paths
 */
function normalizeProductImage($imagePath) {
    if (empty($imagePath)) {
        return '';
    }
    
    // Base64 data - leave as-is
    if (strpos($imagePath, 'data:image') === 0) {
        return $imagePath;
    }
    
    // External URLs - leave as-is
    if (strpos($imagePath, 'http') === 0) {
        return $imagePath;
    }
    
    // Fix backslashes to forward slashes
    $imagePath = str_replace('\\', '/', $imagePath);
    
    // Remove leading slashes
    $imagePath = ltrim($imagePath, '/');
    
    // Remove 'ecoms/' if it's at the start
    if (strpos($imagePath, 'ecoms/') === 0) {
        $imagePath = substr($imagePath, 6);
    }
    
    // Typical paths that work on both environments
    // pics_ecom/image.jpg ✅
    // uploads/image.jpg ✅
    // product_images/image.jpg ✅
    
    return $imagePath;
}
?>
